From 5a6a73e3190cac103906b479d56129413e5ef190 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Mon, 8 Jun 2020 21:37:35 -0700 Subject: [PATCH] Replace os.urandom(32).hex() with secrets.token_hex(32) --- datasette/app.py | 5 +++-- docs/config.rst | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/datasette/app.py b/datasette/app.py index 120091f7..633ca4fe 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -8,6 +8,7 @@ import itertools import json import os import re +import secrets import sys import threading import traceback @@ -186,7 +187,7 @@ class Datasette: assert config_dir is None or isinstance( config_dir, Path ), "config_dir= should be a pathlib.Path" - self._secret = secret or os.urandom(32).hex() + self._secret = secret or secrets.token_hex(32) self.files = tuple(files) + tuple(immutables or []) if config_dir: self.files += tuple([str(p) for p in config_dir.glob("*.db")]) @@ -299,7 +300,7 @@ class Datasette: self._register_renderers() self._permission_checks = collections.deque(maxlen=200) - self._root_token = os.urandom(32).hex() + self._root_token = secrets.token_hex(32) def sign(self, value, namespace="default"): return URLSafeSerializer(self._secret, namespace).dumps(value) diff --git a/docs/config.rst b/docs/config.rst index 56b38613..ab14ea7b 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -302,7 +302,7 @@ Or:: One way to generate a secure random secret is to use Python like this:: - $ python3 -c 'import os; print(os.urandom(32).hex())' + $ python3 -c 'import secrets; print(secrets.token_hex(32))' cdb19e94283a20f9d42cca50c5a4871c0aa07392db308755d60a1a5b9bb0fa52 Plugin authors make use of this signing mechanism in their plugins using :ref:`datasette_sign` and :ref:`datasette_unsign`.