Repository navigation
Inventory Trusted Types violations in system tests #3194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c3401a9
Inventory Trusted Types violations in system tests
jeremy 9407b10
Drain Trusted Types violations before Capybara resets the session
jeremy 6fa278f
Collect Trusted Types violations from the test's own window, and keep…
jeremy 3739578
Unregister the Trusted Types listener even when draining fails
jeremy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| require "test_helper" | ||
| require "rack/lint" | ||
|
|
||
| class TrustedTypesReportOnlyTest < ActiveSupport::TestCase | ||
| HEADER = "content-security-policy-report-only" | ||
| DIRECTIVE = "require-trusted-types-for 'script'" | ||
|
|
||
| test "adds the directive as the only report-only policy when the app sets none" do | ||
| headers = call_with "text/html; charset=utf-8" | ||
|
|
||
| assert_equal DIRECTIVE, headers[HEADER] | ||
| end | ||
|
|
||
| test "stacks a second header field beside an existing report-only policy" do | ||
| headers = call_with "text/html", HEADER => "default-src 'self'" | ||
|
|
||
| assert_equal [ "default-src 'self'", DIRECTIVE ], headers[HEADER] | ||
| end | ||
|
|
||
| test "leaves non-document responses alone" do | ||
| headers = call_with "application/json" | ||
|
|
||
| assert_nil headers[HEADER] | ||
| end | ||
|
|
||
| private | ||
| def call_with(content_type, extra_headers = {}) | ||
| inner = ->(env) { [ 200, { "content-type" => content_type, **extra_headers }, [ "" ] ] } | ||
| app = Rack::Lint.new(TrustedTypesReportOnly.new(inner)) | ||
|
|
||
| _status, headers, body = app.call(Rack::MockRequest.env_for("/")) | ||
| body.close | ||
| headers | ||
| end | ||
| end |
130 changes: 130 additions & 0 deletions
130
test/test_helpers/trusted_types_violations_test_helper.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| # Inventories the Trusted Types violations system tests trip, without failing | ||
| # any test over them. | ||
| # | ||
| # The test environment serves the report-only Trusted Types policy (see | ||
| # config/initializers/content_security_policy.rb). Before any page script runs, | ||
| # a listener injected over CDP records each `securitypolicyviolation` for that | ||
| # policy into sessionStorage, which survives full page loads. Teardown drains it | ||
| # into tmp/trusted_types_violations.jsonl, one line per violation, and the run | ||
| # ends by grouping those by sink and source location into | ||
| # tmp/trusted_types_violations.json. | ||
| # | ||
| # Only the default Capybara session is observed. | ||
| module TrustedTypesViolationsTestHelper | ||
| extend ActiveSupport::Concern | ||
|
|
||
| LOG = Rails.root.join("tmp/trusted_types_violations.jsonl") | ||
| INVENTORY = Rails.root.join("tmp/trusted_types_violations.json") | ||
| STORAGE_KEY = "trusted-types-violations" | ||
|
|
||
| LISTENER = <<~JS | ||
| window.addEventListener("securitypolicyviolation", (event) => { | ||
| if (!/trusted-types/.test(event.effectiveDirective)) return | ||
|
|
||
| try { | ||
| const violations = JSON.parse(sessionStorage.getItem("#{STORAGE_KEY}") || "[]") | ||
| violations.push({ | ||
| directive: event.effectiveDirective, | ||
| sample: event.sample, | ||
| source: event.sourceFile, | ||
| line: event.lineNumber, | ||
| column: event.columnNumber, | ||
| page: location.pathname | ||
| }) | ||
| sessionStorage.setItem("#{STORAGE_KEY}", JSON.stringify(violations)) | ||
| } catch {} | ||
| }, true) | ||
| JS | ||
|
|
||
| DRAIN = <<~JS | ||
| try { | ||
| const violations = sessionStorage.getItem("#{STORAGE_KEY}") || "[]" | ||
| sessionStorage.removeItem("#{STORAGE_KEY}") | ||
|
jeremy marked this conversation as resolved.
|
||
| return violations | ||
| } catch { | ||
| return "[]" | ||
| } | ||
| JS | ||
|
|
||
| class << self | ||
| def reset | ||
| FileUtils.rm_f [ LOG, INVENTORY ] | ||
| end | ||
|
|
||
| def record(test, violations) | ||
| if violations.any? | ||
| lines = violations.map { |violation| violation.merge("test" => test).to_json + "\n" } | ||
| File.open(LOG, "a") { |file| file.write(lines.join) } | ||
| end | ||
| end | ||
|
|
||
| def write_inventory | ||
| if LOG.exist? | ||
| violations = LOG.each_line.map { |line| JSON.parse(line) } | ||
| INVENTORY.write JSON.pretty_generate(inventory_of(violations)) | ||
| end | ||
|
jeremy marked this conversation as resolved.
Outdated
|
||
| end | ||
|
|
||
| private | ||
| def inventory_of(violations) | ||
| groups = violations.group_by { |violation| [ sink_of(violation), location_of(violation) ] } | ||
|
|
||
| { "violations" => violations.size, | ||
| "by_sink" => violations.group_by { |violation| sink_of(violation) }.transform_values(&:size).sort_by { -it.last }.to_h, | ||
| "sites" => groups.map { |(sink, location), group| site(sink, location, group) }.sort_by { -it["count"] } } | ||
| end | ||
|
|
||
| def site(sink, location, violations) | ||
| { "sink" => sink, | ||
| "source" => location, | ||
| "count" => violations.size, | ||
| "pages" => violations.map { it["page"] }.uniq.sort, | ||
| "tests" => violations.map { it["test"] }.uniq.sort, | ||
| "example" => violations.first["sample"] } | ||
| end | ||
|
|
||
| # Chromium samples read "<sink>|<first 40 characters written>". | ||
| def sink_of(violation) | ||
| violation["sample"].to_s.split("|", 2).first.presence || violation["directive"] | ||
| end | ||
|
|
||
| def location_of(violation) | ||
| [ script_of(violation["source"]), violation["line"], violation["column"] ].join(":") | ||
| end | ||
|
|
||
| # Drop the origin, which changes with the test server's port, and the | ||
| # asset digest, which changes with every build. | ||
| def script_of(source) | ||
| path = URI.parse(source.to_s).path.presence || source.presence || "(inline)" | ||
| path.sub(/-\h{8,}(?=\.js\z)/, "") | ||
| rescue URI::InvalidURIError | ||
| source | ||
| end | ||
| end | ||
|
|
||
| included do | ||
| TrustedTypesViolationsTestHelper.reset | ||
| Minitest.after_run { TrustedTypesViolationsTestHelper.write_inventory } | ||
|
|
||
| setup do | ||
| @trusted_types_listener = page.driver.browser.execute_cdp("Page.addScriptToEvaluateOnNewDocument", source: LISTENER)["identifier"] | ||
| end | ||
| end | ||
|
|
||
| # Teardown callbacks run after Capybara has reset the session to a blank | ||
| # page, so drain before then. | ||
| def before_teardown | ||
| TrustedTypesViolationsTestHelper.record "#{self.class.name}##{name}", drain_trusted_types_violations | ||
| page.driver.browser.execute_cdp("Page.removeScriptToEvaluateOnNewDocument", identifier: @trusted_types_listener) | ||
|
jeremy marked this conversation as resolved.
Outdated
|
||
| ensure | ||
| super | ||
| end | ||
|
|
||
| private | ||
| def drain_trusted_types_violations | ||
| JSON.parse(page.execute_script(DRAIN)) | ||
| rescue Selenium::WebDriver::Error::WebDriverError => error | ||
| warn "Trusted Types inventory lost #{name}'s violations: #{error.class}" | ||
| [] | ||
| end | ||
| end | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.