2023-12

2023-12-14 Projets Django de l’administration française

django-dsfr

Django-dsfr est une application django permettant d’utiliser le système de design de l’État dans des projets Django.

Elle a été développée dans le cadre du défi Open Collectivités et est un travail en cours (les composants sont actuellement développés au fur et à mesure de leur utilisation dans le cadre d’Open Collectivités), cf. la page Composants.

.._djanfo_magicauth:

django-magicauth

Password-less authentication for Django. An email with a magic link allows a secure login

2023-12-13 Django: Sanitize incoming HTML fragments with nh3

A fairly common situation in a Django project is where you need to store and serve arbitrary HTML fragments.

These often come from forms with rich text editors (using HTML’s contenteditable).

It’s insecure to trust user-generated HTML fragments since they can contain naughty content like:

<script src=https://example.com/evil.js></script>

A page containing this content would execute the arbitrary code in evil.js, possibly stealing user details. This technique is a Cross-Site Scripting (XSS) attack.

Whilst a strong Content Security Policy can reduce the possible effects of arbitrary content, it’s still best to “sanitize” incoming HTML fragments, allowing only safe content into your database.

This way, there’s no chance of future changes allowing XSS attacks through.

For years, the Django community has relied on the Bleach package for HTML sanitization, either directly or via django-bleach. But in January this year, Will Kahn-Greene, the Bleach maintainer, announced it was deprecated. This move is due to the underlying HTML parser package, html5lib, going unmaintained.

Since 2021, there has been a new package for the task, nh3, created and maintained by Messense Lv. Playing off of “bleach”, it is named after the chemical formula for Ammonia, which is also the name for its underlying HTML parser package.

Both are built in Rust, making nh3 about 20 times faster than the pure-Python Bleach.

Ammonia copies a lot from Bleach, even parts of the API, hence its similar name.

Let’s look at how to use nh3 for HTML sanitisation in Django forms. You can adapt this approach to other situations, such as in DRF serializers.