Skip to content

Commit

Permalink
feat(karma): use Trusted Types policy when loading scripts for Karma
Browse files Browse the repository at this point in the history
When the Karma plugin is used in a testing environment that enforces
Trusted Types, its loadFile functionality currently fails due to a
Trusted Types violation when assigning to script.textContent. This makes
it impossible to use the plugin with integration tests that ensure an
application is compatible with Trusted Types.

This is fixed by creating a Trusted Types policy specifically for the
Karma plugin, and use it to promote any loaded scripts to a TrustedScript
before assigning to script.textContent. This is done in a way that is
backwards compatible:
- The policy is `null` in browsers that don't yet support Trusted Types,
  in which case the original script string is used as before.
- When Trusted Types are supported in the browser but not enforced by
  the application, the browser treats the TrustedScript as if it were a
  string when it is assigned to script.textContent.
  • Loading branch information
bjarkler authored and alexeagle committed Oct 9, 2020
1 parent 4fc0cc4 commit af9feb4
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/karma/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,31 @@ function initConcatJs(logger, emitter, basePath, hostname, port) {
// global variables, even with 'use strict'; (unlike eval).
bundleFile.content = `
(function() { // Hide local variables
// Use policy to support Trusted Types enforcement.
var policy = null;
if (window.trustedTypes) {
try {
policy = window.trustedTypes.createPolicy('bazel-karma', {
createScript: function(s) { return s; }
});
} catch (e) {
// In case the policy has been unexpectedly created before, log the error
// and fall back to the old behavior.
console.log(e);
}
}
// IE 8 and below do not support document.head.
var parent = document.getElementsByTagName('head')[0] ||
document.documentElement;
function loadFile(path, src) {
var trustedSrc = policy ? policy.createScript(src) : src;
try {
var script = document.createElement('script');
if ('textContent' in script) {
script.textContent = src;
script.textContent = trustedSrc;
} else {
// This is for IE 8 and below.
script.text = src;
script.text = trustedSrc;
}
parent.appendChild(script);
// Don't pollute the DOM with hundreds of <script> tags.
Expand Down

0 comments on commit af9feb4

Please sign in to comment.