Skip to content

Commit

Permalink
Validate settings.json keys on startup, closes #1816
Browse files Browse the repository at this point in the history
Refs #1814
  • Loading branch information
simonw committed Sep 19, 2022
1 parent ddc999a commit df851c1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
4 changes: 4 additions & 0 deletions datasette/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,10 @@ def __init__(
raise StartupError("config.json should be renamed to settings.json")
if config_dir and (config_dir / "settings.json").exists() and not settings:
settings = json.loads((config_dir / "settings.json").read_text())
# Validate those settings
for key in settings:
if key not in DEFAULT_SETTINGS:
raise StartupError("Invalid setting '{key}' in settings.json")
self._settings = dict(DEFAULT_SETTINGS, **(settings or {}))
self.renderers = {} # File extension -> (renderer, can_render) functions
self.version_note = version_note
Expand Down
20 changes: 18 additions & 2 deletions tests/test_config_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from datasette.app import Datasette
from datasette.cli import cli
from datasette.utils.sqlite import sqlite3
from datasette.utils import StartupError
from .fixtures import TestClient as _TestClient
from click.testing import CliRunner

Expand All @@ -27,9 +28,8 @@ def extra_template_vars():


@pytest.fixture(scope="session")
def config_dir_client(tmp_path_factory):
def config_dir(tmp_path_factory):
config_dir = tmp_path_factory.mktemp("config-dir")

plugins_dir = config_dir / "plugins"
plugins_dir.mkdir()
(plugins_dir / "hooray.py").write_text(PLUGIN, "utf-8")
Expand Down Expand Up @@ -77,7 +77,23 @@ def config_dir_client(tmp_path_factory):
),
"utf-8",
)
return config_dir


def test_invalid_settings(config_dir):
previous = (config_dir / "settings.json").read_text("utf-8")
(config_dir / "settings.json").write_text(
json.dumps({"invalid": "invalid-setting"}), "utf-8"
)
try:
with pytest.raises(StartupError):
ds = Datasette([], config_dir=config_dir)
finally:
(config_dir / "settings.json").write_text(previous, "utf-8")


@pytest.fixture(scope="session")
def config_dir_client(config_dir):
ds = Datasette([], config_dir=config_dir)
yield _TestClient(ds)

Expand Down

0 comments on commit df851c1

Please sign in to comment.