Security
Hologram protects your pages against cross-site scripting and request forgery by default, with nothing to configure. This page lists what it does for you and where to read more.
What Hologram Does for You
- Escaping. Every value interpolated into text or a quoted attribute is HTML-escaped, so user input renders as text and can't become markup. Inside a
<script>or<style>element, a value in quotes is escaped for that language too. See "Security: Automatic HTML Escaping" in the Template Syntax documentation.trust_html/1turns it off for HTML you trust. See "Trusted HTML" there. - SQL injection. A query sends every value your code gives it to Postgres as a parameter, apart from the SQL text, so user input can't change what the query does. Table and column names come from your entity types, never from a value. See "Pinning Values" in the Queries documentation.
- Access rules. If your app uses the data layer, the server checks every read and write a user makes against the rules of your entity types, and denies what no rule allows. See Data Layer Access below.
- CSRF protection. Every command and every batch of data layer writes carries a token tied to the user's session, and the server refuses one without a valid token. See CSRF Protection below.
- Content Security Policy. Hologram sends a strict policy with every page a visit starts on, so a script an attacker gets into the page doesn't run. See Content Security Policy below.
- Cookies. A cookie you set is HTTP-only, secure and
SameSite=Laxunless you say otherwise. Its value isn't signed, so a user can read and change it. Treat it like any other client-supplied data. See the Cookies documentation. - Session. Only the server writes session data, in
init/3, commands and middleware, never by client code. A user can't edit it, though they can delete it or send back an older copy. Whether a user can read it depends on how it's stored, which the Session documentation describes.
Escaping makes a value safe where it stands as text. It can't help when a value ends up somewhere that is itself code or a URL:
- An interpolation without quotes in a
<script>or<style>, as inconst id = {@id};. A value like1;alert(document.domain)runs as code, and the page's nonce covers it, since the script is yours. Put the value in quotes,"{@id}", and convert it in JavaScript, or pass it through JS interop. - User input in code you pass to
JS.eval/1orJS.exec/1, as inJS.exec("highlight('#{query}')"). The string runs as code, with the page's nonce. Pass the value as an argument withJS.call/3instead. The~JSsigil doesn't interpolate, so its code is always yours. - A user-supplied URL in
hreforsrc. It can be ajavascript:URL. Check the scheme before you render it. - Attribute names or tag names taken from user input, through an attribute spread or a dynamic tag. Build them from values you control.
- HTML marked with
trust_html/1. It goes on the page as markup, unescaped and unsanitized, with its<script>elements removed. Sanitize anything a user wrote before you trust it. - A statement you build for
DB.sqlfrom user input, as inDB.sql("SELECT * FROM hologram_data.task WHERE title = '#{title}'"). Write$1in the statement and pass the value in the list after it:DB.sql("SELECT * FROM hologram_data.task WHERE title = $1", [title]).
CSRF Protection
A cross-site request forgery makes a logged-in user's browser send a request your app trusts, from a page on another site. Hologram guards commands and data layer writes against it. The page a visit starts on carries a token tied to the user's session, the runtime sends it with every command and every batch of writes, and the server answers a request whose token doesn't match with a 403. The token is masked anew on every page load, so it never repeats in the markup.
A page load carries no token, whether it's the first one of a visit or a navigation. Another site can link to any of your pages, and the browser loads it as the logged-in user. So don't let middleware or init/3 act on the user's behalf, such as by deleting a post or sending an email. Do that in a command, which the token protects. A link whose URL carries its own secret, like an email confirmation link, is fine, since another site can't know it.
The realtime stream needs no token either. The server refuses its handshake without a session, and accepts only the subscriptions it signed for that tab and user. In embedded mode, a native form that posts to a Phoenix route gets Phoenix's own CSRF protection.
Content Security Policy
Hologram sends a Content Security Policy with every page a visit starts on. The policy tells the browser which scripts may run, so the browser refuses a script an attacker gets into a page, through an escaping bug for example. It needs no configuration, and your templates need no changes.
The Default Policy
base-uri 'none'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'nonce-R4nd0m...' 'strict-dynamic' 'unsafe-inline' https:
What each directive does:
base-uri 'none'- no<base>element, which could otherwise redirect the page's relative script URLs.form-action 'self'- forms submit only to your own site, so an injected form can't send what users type somewhere else.frame-ancestors 'self'- only your own pages can put your pages in an iframe, which stops clickjacking.object-src 'none'- no plugins through<object>or<embed>.script-src 'nonce-...' 'strict-dynamic'- a script runs only if it carries the page's nonce, a random value Hologram generates for every page load, or if a script carrying it loaded it. This is what stops injected scripts.'unsafe-inline'andhttps:are fallbacks for browsers too old for nonces or'strict-dynamic', and every current browser ignores them.
Nothing restricts images, fonts, styles, media, the iframes you embed, or the servers the page talks to, since none of them run code. Google Fonts, a CDN stylesheet, an analytics pixel, a YouTube embed and inline style attributes all work with no configuration.
This is the strict policy Google and OWASP recommend. It passes Lighthouse, Google's CSP Evaluator and Mozilla's HTTP Observatory. Their one note is that it names no endpoint for violation reports, which only your app can provide. Configuring the Policy below shows how.
Nonces
Hologram puts the page's nonce on every <script> element it renders. That covers the ones in your layouts and templates, its own runtime and bundles, and the scripts the client creates when it navigates, so inline and third-party scripts in your templates work as written:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
</script>
Hologram removes a nonce you write yourself on a <script>, <style> or <link>. The policy lists only the page's own nonce, so yours would never match.
The default policy doesn't restrict styles, so Hologram adds no nonce to <style> and <link> elements. If you allow only styles that carry the page's nonce, Hologram adds it to every <style> and <link> it renders:
config :hologram, content_security_policy: [style_src: [:self, :nonce]]
The same goes for :nonce in style_src_elem, or in default_src if you set neither style_src_elem nor style_src. The browser checks styles against the first of those three that your policy has, and so does Hologram.
What the policy blocks, by design, is code that doesn't come through a nonced script: inline event handler attributes like onclick="...", javascript: URLs, and scripts a third-party script writes into the page with document.write. Use Hologram's event bindings, such as $click, instead of handler attributes.
JavaScript interop works under the policy without 'unsafe-eval'. JS.eval/1, JS.exec/1 and the ~JS sigil don't use eval() or new Function(). Hologram runs their code as a script carrying the page's nonce, so the policy trusts it like your own scripts. The data Hologram sends between the server and the client travels as JSON.
Configuring the Policy
config :hologram, content_security_policy: [
form_action: [:self, "https://checkout.stripe.com"],
img_src: [:self, "https://images.example.com", "data:"]
]
How the config maps to the header:
- Each key is a directive, written with underscores:
img_srcforimg-src. - Each value is a list of sources. An atom is a keyword, written quoted with hyphens:
:selfbecomes'self',:unsafe_inlinebecomes'unsafe-inline', and:noncebecomes the page's nonce. A string is written as it is, such as a host, a scheme like"data:"or a sandbox flag. A tuple like{:sha256, "..."}is a hash source.upgrade_insecure_requeststakes no sources, so it takestrueinstead of a list. - A directive you give replaces Hologram's default for that directive. The others keep their defaults. A directive Hologram doesn't set, like
img_srcabove, is unrestricted until you give it, so giving one limits that kind of request to the sources you list. falseremoves a directive. For example,frame_ancestors: falsedrops the policy's limit on who can embed your pages. Another header can still limit it, such asx-frame-options. In embedded mode, Phoenix'sput_secure_browser_headerssends one.config :hologram, content_security_policy: falsesends no policy at all, and the page then carries no nonce.
The policy is read for every page, so unlike the compiler settings it also works from config/runtime.exs. A malformed config fails your app's start with an error naming the entry. So does one under which no Hologram page could work, such as a script_src that allows neither the page's nonce nor inline scripts and your own origin, a default_src: [:none] that blocks the requests Hologram makes to your server, or a sandbox without "allow-scripts" and "allow-same-origin".
Common additions:
config :hologram, content_security_policy: [
# The servers your client code talks to: your own, and an analytics service
connect_src: [:self, "https://analytics.example.com"],
# Your pages embedded on a partner's site
frame_ancestors: [:self, "https://partner.example.com"],
# Violation reports sent to an endpoint you run or a reporting service
report_uri: ["https://csp-reports.example.com"],
# Stylesheets and style elements limited to your own site and the page's nonce,
# with inline style attributes still allowed, which style_src alone would block
style_src: [:self, :nonce],
style_src_attr: [:unsafe_inline]
]
Check the hosts a third-party service needs in its own docs before limiting a directive. An analytics service often sends to several domains.
Most apps never change script_src. Every script Hologram renders carries the nonce, and with 'strict-dynamic' the scripts those load are trusted too. When you do change it, restate the parts of the default you want to keep, since a directive you give replaces the default: script_src: [:nonce, :strict_dynamic, :unsafe_inline, "https:", ...].
Hologram's own forms submit through $submit and never post natively, so form-action 'self' doesn't affect them. A native <form> that posts to another site needs that site in form_action. So does a native form whose route answers with a redirect to another site, since browsers check the redirect too. Stripe Checkout's quickstart and some OAuth sign-in buttons work that way. Hologram doesn't need the form for either. For a checkout, a command creates the session and puts an action with its URL, and the action sends the browser there with JS.set(:window, :location, url). For a sign-in, a plain link to the route works.
Trusted Types
Trusted Types extends the protection to the browser APIs that turn strings into code or markup, like innerHTML and script.src. When it's enforced, the browser refuses a plain string there and takes only a value that a named policy created. Turn it on with:
config :hologram, content_security_policy: [require_trusted_types_for: [:script]]
Hologram's runtime writes its scripts, and HTML marked with trust_html/1, through a Trusted Types policy named hologram, so it keeps working under enforcement. A third-party script that writes raw HTML needs a default policy of your own. Without a trusted_types directive any policy name is allowed. When you give one to limit the names, Hologram adds hologram to it:
config :hologram, content_security_policy: [
require_trusted_types_for: [:script],
trusted_types: ["default"]
]
Under enforcement the browser also refuses a few attributes your templates can write, on elements Hologram creates on the client: srcdoc on an <iframe>, on* event handler attributes, which the policy blocks anyway, and href on an SVG <script>.
Who Sends the Policy
- On a page a visit starts on, Hologram sends exactly the policy the config describes. In embedded mode, it replaces any
content-security-policyheader a plug ahead of it set. Hologram leaves acontent-security-policy-report-onlyheader alone. One without the page's nonce reports every Hologram script. - Navigations, commands and the realtime stream carry no policy, since the browser keeps the one of the page the visit started on.
- With
content_security_policy: false, Hologram sends no policy. In embedded mode, it leaves alone any policy a plug ahead of it set. Such a policy carries no nonce, so it blocks Hologram's scripts unless it allows them another way. put_response_header(server, "content-security-policy", ...)raises in a page, a layout, a component or a command. The policy belongs in config. The browser applies the policy of the page a visit starts on, and Hologram's navigation keeps it, so a policy one page set would hold only when that page came first. A response that middleware or a page'sinit/3ends withput_statuscan carry one, unless Hologram shows an error page in its place.
Data Layer Access
This section applies if your app uses Hologram's data layer. With another data source, you check access in your own code.
Access Rules
Each entity type says who may read and write its entities, with allow lines. Nobody may do what no line allows, so an entity type with no lines is closed to every user. The server checks every write an action makes, whatever the browser did with it, and it never sends a browser an entity its user may not read. The rules also apply to reads and writes in init/3, middleware, commands and the jobs a user creates. See Access Control.
The rules are part of the code the browser gets, along with the names of your entity types, attributes and roles. Anyone who can open your app can read them, signed in or not, so don't write a secret into one. This doesn't weaken the rules, since the server checks every read and write with its own copy.
Going Past the Rules
Two things on the server go past the access rules, so check access yourself wherever you use them for a user:
trust()reads or writes on the server's own authority. Browser code can't claim it. A trusted read can return entities the user may not see, so keep its result on the server.DB.sqlsees every row and every column, server-only ones included. Limit the rows in the SQL itself, and select only what the browser may see. See Reading Data.
Server-Only Attributes
A user who may read an entity gets all of its attributes, except the ones marked with server_only: true. Mark attributes like password hashes and API tokens:
attribute :api_token, :string, optional: true, server_only: true
Hologram removes these values from every entity it sends to the browser, also when the entity is in the state or in an action's params. It can't do that for a value you copy out of an entity. put_state(component, :token, user.api_token) sends the token to the browser. See Server-Only Attributes in the Entities documentation.
What the Client Can Fake
Everything a request carries comes from the client and can be faked: a page's params, the module, name, target and params of a command, the request headers, the cookies, and the host. Users can read and change client code too, since it runs in their browser, so authorize on the server, never in an action alone. Decide who may see a page in its middleware or init/3, and who may run a command in middleware or in the command itself. For the entities an action writes through the data layer, your access rules decide, and the server checks them.
A command can be sent to any component, not only through the buttons a page shows, and only the middleware of the component it names runs. A gate on a page doesn't cover its components' commands, so attach it to each component that needs it. The Middleware documentation shows how.
The host is client-supplied even with no proxy in front. Validate it against an allowlist before using it for a security decision, such as picking a tenant, and never build a security-sensitive URL from it, such as a password reset link in an email.
Reporting Vulnerabilities
To report a security vulnerability in Hologram, see the Reporting Vulnerabilities page.