In order to take advantage of this feature, we need to specify CDN settings.

Once CDN mode is on, all the will return absolute URLs.

  1. <link href="https://123.cloudfront.net/assets/application-9ab4d1f57027f0d40738ab8ab70aba86.css" type="text/css" rel="stylesheet">

Subresource Integrity

A CDN can dramatically improve page speed, but it can potentially open a security breach. If the CDN that we’re using is compromised and serves evil javascript or stylesheet files, we’re exposing our users to security attacks like Cross Site Scripting (XSS).

To solve this problem, browsers vendors introduced a defense called .

When enabled, the browser verifies that the checksum of the downloaded file, matches with the declared one.

The output will be:

  1. <script integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript" crossorigin="anonymous"></script>

By default, Hanami sets a Content-Security-Policy header which does not allow for the execution of external JavaScript code.

Let’s say we want to use Bootstrap in our web application, we have to explicitly allow for the use of the relevant CDNs in app/web/application.rb by appending them in the script-src field:

  1. script-src 'self' \
  2. https://code.jquery.com \
  3. https://cdnjs.cloudflare.com \
  4. }

Read more about the CSP header in the .

The security problem described above doesn’t concern only CDNs, but local files too. Imagine we have a compromised file system and someone was able to replace our javascripts with evil files: we would be vulnerable to the same kind of attack.

  1. <script src="/assets/application-92cab02f6d2d51253880cd98d91f1d0e.js" type="text/javascript" integrity="sha256-WB2pRuy8LdgAZ0aiFxLN8DdfRjKJTc4P4xuEw31iilM=" crossorigin="anonymous"></script>

To turn off this feature, or to configure it, please have a look at the production block in apps/web/application.rb

  1. class Application < Hanami::Application
  2. configure :production do
  3. assets do
  4. subresource_integrity :sha256
  5. end
  6. end
  7. end

By removing or commenting that line, the feature is turned off.

We can choose one or more checksum algorithms:

With this setting, Hanami will render integrity HTML attribute with two values: one for SHA256 and one for SHA512.

  1. <script src="/assets/application-92cab02f6d2d51253880cd98d91f1d0e.js" type="text/javascript" integrity="sha256-WB2pRuy8LdgAZ0aiFxLN8DdfRjKJTc4P4xuEw31iilM= sha512-4gegSER1uqxBvmlb/O9CJypUpRWR49SniwUjOcK2jifCRjFptwGKplFWGlGJ1yms+nSlkjpNCS/Lk9GoKI1Kew==" crossorigin="anonymous"></script>

Please note that checksum calculations are CPU intensive, so adding an additional subresource_integrity scheme will extend the time it takes to precompile assests, and therefore deploy. We suggest leaving the default setting (:sha256).