twitter / hogan.js

A compiler for the Mustache templating language
http://twitter.github.io/hogan.js
Apache License 2.0
5.14k stars 431 forks source link

Security policy problem inside a Chrome extension #135

Closed simov closed 11 years ago

simov commented 11 years ago
Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".
 compiler.js:291

Chrome Extensions Content Security Policy Content Security Policy 1.1

I can alter the policy string inside my manifest.json

"content_security_policy": "script-src 'unsafe-eval'; object-src 'self'"

but I shouldn't do that according to the chrome's documentation.

oreoshake commented 11 years ago

If you load the same page in Firefox, it will provide more information about what the specific violation is (line number code snippet).

The object-src 'self' seems unrelated? That's usually flash related/Java-related.

simov commented 11 years ago
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-security-policy" content="script-src 'self'" />
    <script src="/jslib/hoganjs/template.js" type="text/javascript" charset="utf-8"></script>
    <script src="/jslib/hoganjs/compiler.js" type="text/javascript" charset="utf-8"></script>
    <script src="security-policy.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>

</body>
</html>

security-policy.js

var template = Hogan.compile('<p>{{hi}}</p>');
var output = template.render({hi: 'hello'});
console.log(output);

If you comment out the meta tag you get <p>hello</p> in the console, but with the security policy enabled you get the above error compiler.js:291. That's on Chrome, Firefox does not implement defining policy inside the html. Inside a Chrome extension this policy is enabled by default i.e. I don't define it inside the html but the error is exactly the same.

manu commented 11 years ago

We are using https://npmjs.org/package/helmet and it gives

Error: call to Function() blocked by CSP

https://developer.mozilla.org/en-US/docs/Web/Apps/CSP say we cannot use the Function() constructor.

Can you check https://github.com/twitter/hogan.js/blob/master/web/1.0.0/hogan.js#L387

oreoshake commented 11 years ago

Just add 'unsafe-eval' to your policy. It is the only way it will work.

unsafe-eval is not ideal, but it's much less risky than unsafe-inline. This is a common problem, especially with template languages. We're working w/ the w3c on ways to solve this. That being said, I'm sure there's a possible code fix. This is just a bandaid solution.