How do I improve my plugin's security by enabling autoescape?

This FAQ entry targets plugin developers.

Starting with OctoPrint 1.11.0, OctoPrint will ship with auto-escaping all injected template variables and other included expressions in its template system. For 1.11.0 and 1.12.0, this will only be done for bundled plugins and those third party plugins that have opted into autoescaping. Starting with OctoPrint 1.13.0 however, third party plugins will have to opt out in order to not have autoescaping enabled on their templates.

What is autoescaping supposed to do?

Autoescaping means that all variables and other expressions you inject into your plugin's HTML code inside of your defined templates get automatically escaped so that HTML code contained in them won't be run inside OctoPrint's browser UI.

So far, this had to be done manually by escaping each individual include that might contain user input via |e. As this repeatedly has lead to overlooked places where critical variables might be exposed in an unsafe way, even in OctoPrint's core UI itself, with version 1.11.0 OctoPrint switches to autoescaping to reduce its Cross-Site Scripting (XSS) attack surface.

Why is this opt-in for third party plugins for now?

Your plugin might not yet be prepared for auto-escaping. If you have any includes that also contain HTML, and that's intended, auto-escaping your plugin could break it. Therefore, OctoPrint 1.11.0 will only offer to opt into auto-escaping, and won't enforce this until OctoPrint 1.13.0. This will give you as the plugin maintainer plenty of time to test your plugin with auto-escape enabled and ensure everything works fine.

For the sake of security, you should get to this ASAP!

How do I opt-into autoescaping?

Add the following method to your TemplatePlugin implementation:

def is_template_autoescaped(self):
  return True

I need to be able to include some HTML from a variable in a template, but only in some specific places, can I do that?

Yes. Similar to the manual escape filter |e, you can also mark certain includes as safe code by adding |safe. Make extra sure to only do that in code that you have under control. Don't mark any variables or other output as safe that can be changed by user input!

How do I opt-out of autoescaping?

You really shouldn't be doing that, as it increases the risk of making your plugin vulnerable to XSS and thus a security risk for the whole OctoPrint instance.

If it's only for some includes that you need to be able to allow HTML code, please see the previous section about allowing that only in specific places through the use of |safe.

If you really absolutely need to disable autoescaping you can find the information on how to do that below.

How to opt-out of auto-escaping (THIS IS A SECURITY RISK!)

Add the following method to your TemplatePlugin implementation:

def is_template_autoescaped(self):
  return True

Further reading