| 1 |
from bs4 import BeautifulSoup as Soup |
| 2 |
import json |
| 3 |
import pytest |
| 4 |
import re |
| 5 |
from .fixtures import make_app_client, app_client |
| 6 |
|
| 7 |
|
| 8 |
@pytest.fixture |
| 9 |
def canned_write_client(tmpdir): |
| 10 |
template_dir = tmpdir / "canned_write_templates" |
| 11 |
template_dir.mkdir() |
| 12 |
(template_dir / "query-data-update_name.html").write_text( |
| 13 |
""" |
| 14 |
{% extends "query.html" %} |
| 15 |
{% block content %}!!!CUSTOM_UPDATE_NAME_TEMPLATE!!!{{ super() }}{% endblock %} |
| 16 |
""", |
| 17 |
"utf-8", |
| 18 |
) |
| 19 |
with make_app_client( |
| 20 |
extra_databases={"data.db": "create table names (name text)"}, |
| 21 |
template_dir=str(template_dir), |
| 22 |
metadata={ |
| 23 |
"databases": { |
| 24 |
"data": { |
| 25 |
"queries": { |
| 26 |
"canned_read": {"sql": "select * from names"}, |
| 27 |
"add_name": { |
| 28 |
"sql": "insert into names (name) values (:name)", |
| 29 |
"write": True, |
| 30 |
"on_success_redirect": "/data/add_name?success", |
| 31 |
}, |
| 32 |
"add_name_specify_id": { |
| 33 |
"sql": "insert into names (rowid, name) values (:rowid, :name)", |
| 34 |
"write": True, |
| 35 |
"on_error_redirect": "/data/add_name_specify_id?error", |
| 36 |
}, |
| 37 |
"delete_name": { |
| 38 |
"sql": "delete from names where rowid = :rowid", |
| 39 |
"write": True, |
| 40 |
"on_success_message": "Name deleted", |
| 41 |
"allow": {"id": "root"}, |
| 42 |
}, |
| 43 |
"update_name": { |
| 44 |
"sql": "update names set name = :name where rowid = :rowid", |
| 45 |
"params": ["rowid", "name", "extra"], |
| 46 |
"write": True, |
| 47 |
}, |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
}, |
| 52 |
) as client: |
| 53 |
yield client |
| 54 |
|
| 55 |
|
| 56 |
@pytest.fixture |
| 57 |
def canned_write_immutable_client(): |
| 58 |
with make_app_client( |
| 59 |
is_immutable=True, |
| 60 |
metadata={ |
| 61 |
"databases": { |
| 62 |
"fixtures": { |
| 63 |
"queries": { |
| 64 |
"add": { |
| 65 |
"sql": "insert into sortable (text) values (:text)", |
| 66 |
"write": True, |
| 67 |
}, |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
}, |
| 72 |
) as client: |
| 73 |
yield client |
| 74 |
|
| 75 |
|
| 76 |
def test_canned_query_with_named_parameter(app_client): |
| 77 |
response = app_client.get("/fixtures/neighborhood_search.json?text=town") |
| 78 |
assert [ |
| 79 |
["Corktown", "Detroit", "MI"], |
| 80 |
["Downtown", "Los Angeles", "CA"], |
| 81 |
["Downtown", "Detroit", "MI"], |
| 82 |
["Greektown", "Detroit", "MI"], |
| 83 |
["Koreatown", "Los Angeles", "CA"], |
| 84 |
["Mexicantown", "Detroit", "MI"], |
| 85 |
] == response.json["rows"] |
| 86 |
|
| 87 |
|
| 88 |
def test_insert(canned_write_client): |
| 89 |
response = canned_write_client.post( |
| 90 |
"/data/add_name", |
| 91 |
{"name": "Hello"}, |
| 92 |
csrftoken_from=True, |
| 93 |
cookies={"foo": "bar"}, |
| 94 |
) |
| 95 |
assert 302 == response.status |
| 96 |
assert "/data/add_name?success" == response.headers["Location"] |
| 97 |
messages = canned_write_client.ds.unsign( |
| 98 |
response.cookies["ds_messages"], "messages" |
| 99 |
) |
| 100 |
assert [["Query executed, 1 row affected", 1]] == messages |
| 101 |
|
| 102 |
|
| 103 |
@pytest.mark.parametrize( |
| 104 |
"query_name,expect_csrf_hidden_field", |
| 105 |
[ |
| 106 |
("canned_read", False), |
| 107 |
("add_name_specify_id", True), |
| 108 |
("add_name", True), |
| 109 |
], |
| 110 |
) |
| 111 |
def test_canned_query_form_csrf_hidden_field( |
| 112 |
canned_write_client, query_name, expect_csrf_hidden_field |
| 113 |
): |
| 114 |
response = canned_write_client.get(f"/data/{query_name}") |
| 115 |
html = response.text |
| 116 |
fragment = '<input type="hidden" name="csrftoken" value="' |
| 117 |
if expect_csrf_hidden_field: |
| 118 |
assert fragment in html |
| 119 |
else: |
| 120 |
assert fragment not in html |
| 121 |
|
| 122 |
|
| 123 |
def test_insert_with_cookies_requires_csrf(canned_write_client): |
| 124 |
response = canned_write_client.post( |
| 125 |
"/data/add_name", |
| 126 |
{"name": "Hello"}, |
| 127 |
cookies={"foo": "bar"}, |
| 128 |
) |
| 129 |
assert 403 == response.status |
| 130 |
|
| 131 |
|
| 132 |
def test_insert_no_cookies_no_csrf(canned_write_client): |
| 133 |
response = canned_write_client.post("/data/add_name", {"name": "Hello"}) |
| 134 |
assert 302 == response.status |
| 135 |
assert "/data/add_name?success" == response.headers["Location"] |
| 136 |
|
| 137 |
|
| 138 |
def test_custom_success_message(canned_write_client): |
| 139 |
response = canned_write_client.post( |
| 140 |
"/data/delete_name", |
| 141 |
{"rowid": 1}, |
| 142 |
cookies={"ds_actor": canned_write_client.actor_cookie({"id": "root"})}, |
| 143 |
csrftoken_from=True, |
| 144 |
) |
| 145 |
assert 302 == response.status |
| 146 |
messages = canned_write_client.ds.unsign( |
| 147 |
response.cookies["ds_messages"], "messages" |
| 148 |
) |
| 149 |
assert [["Name deleted", 1]] == messages |
| 150 |
|
| 151 |
|
| 152 |
def test_insert_error(canned_write_client): |
| 153 |
canned_write_client.post("/data/add_name", {"name": "Hello"}, csrftoken_from=True) |
| 154 |
response = canned_write_client.post( |
| 155 |
"/data/add_name_specify_id", |
| 156 |
{"rowid": 1, "name": "Should fail"}, |
| 157 |
csrftoken_from=True, |
| 158 |
) |
| 159 |
assert 302 == response.status |
| 160 |
assert "/data/add_name_specify_id?error" == response.headers["Location"] |
| 161 |
messages = canned_write_client.ds.unsign( |
| 162 |
response.cookies["ds_messages"], "messages" |
| 163 |
) |
| 164 |
assert [["UNIQUE constraint failed: names.rowid", 3]] == messages |
| 165 |
# How about with a custom error message? |
| 166 |
canned_write_client.ds._metadata["databases"]["data"]["queries"][ |
| 167 |
"add_name_specify_id" |
| 168 |
]["on_error_message"] = "ERROR" |
| 169 |
response = canned_write_client.post( |
| 170 |
"/data/add_name_specify_id", |
| 171 |
{"rowid": 1, "name": "Should fail"}, |
| 172 |
csrftoken_from=True, |
| 173 |
) |
| 174 |
assert [["ERROR", 3]] == canned_write_client.ds.unsign( |
| 175 |
response.cookies["ds_messages"], "messages" |
| 176 |
) |
| 177 |
|
| 178 |
|
| 179 |
def test_custom_params(canned_write_client): |
| 180 |
response = canned_write_client.get("/data/update_name?extra=foo") |
| 181 |
assert '<input type="text" id="qp3" name="extra" value="foo">' in response.text |
| 182 |
|
| 183 |
|
| 184 |
def test_vary_header(canned_write_client): |
| 185 |
# Dynamic pages vary by credentials, including forms with CSRF cookies. |
| 186 |
for path in ("/data", "/data/update_name"): |
| 187 |
response = canned_write_client.get(path) |
| 188 |
assert { |
| 189 |
value.strip().lower() for value in response.headers["vary"].split(",") |
| 190 |
} == {"cookie", "authorization"} |
| 191 |
|
| 192 |
|
| 193 |
def test_json_post_body(canned_write_client): |
| 194 |
response = canned_write_client.post( |
| 195 |
"/data/add_name", |
| 196 |
body=json.dumps({"name": ["Hello", "there"]}), |
| 197 |
) |
| 198 |
assert 302 == response.status |
| 199 |
assert "/data/add_name?success" == response.headers["Location"] |
| 200 |
rows = canned_write_client.get("/data/names.json?_shape=array").json |
| 201 |
assert rows == [{"rowid": 1, "name": "['Hello', 'there']"}] |
| 202 |
|
| 203 |
|
| 204 |
@pytest.mark.parametrize( |
| 205 |
"headers,body,querystring", |
| 206 |
( |
| 207 |
(None, "name=NameGoesHere", "?_json=1"), |
| 208 |
({"Accept": "application/json"}, "name=NameGoesHere", None), |
| 209 |
(None, "name=NameGoesHere&_json=1", None), |
| 210 |
(None, '{"name": "NameGoesHere", "_json": 1}', None), |
| 211 |
), |
| 212 |
) |
| 213 |
def test_json_response(canned_write_client, headers, body, querystring): |
| 214 |
response = canned_write_client.post( |
| 215 |
"/data/add_name" + (querystring or ""), |
| 216 |
body=body, |
| 217 |
headers=headers, |
| 218 |
) |
| 219 |
assert 200 == response.status |
| 220 |
assert response.headers["content-type"] == "application/json; charset=utf-8" |
| 221 |
assert response.json == { |
| 222 |
"ok": True, |
| 223 |
"message": "Query executed, 1 row affected", |
| 224 |
"redirect": "/data/add_name?success", |
| 225 |
} |
| 226 |
rows = canned_write_client.get("/data/names.json?_shape=array").json |
| 227 |
assert rows == [{"rowid": 1, "name": "NameGoesHere"}] |
| 228 |
|
| 229 |
|
| 230 |
def test_canned_query_permissions_on_database_page(canned_write_client): |
| 231 |
# Without auth only shows three queries |
| 232 |
query_names = { |
| 233 |
q["name"] for q in canned_write_client.get("/data.json").json["queries"] |
| 234 |
} |
| 235 |
assert { |
| 236 |
"canned_read", |
| 237 |
"add_name", |
| 238 |
"add_name_specify_id", |
| 239 |
"update_name", |
| 240 |
"from_async_hook", |
| 241 |
"from_hook", |
| 242 |
} == query_names |
| 243 |
|
| 244 |
# With auth shows four |
| 245 |
response = canned_write_client.get( |
| 246 |
"/data.json", |
| 247 |
cookies={"ds_actor": canned_write_client.actor_cookie({"id": "root"})}, |
| 248 |
) |
| 249 |
assert 200 == response.status |
| 250 |
query_names_and_private = sorted( |
| 251 |
[ |
| 252 |
{"name": q["name"], "private": q["private"]} |
| 253 |
for q in response.json["queries"] |
| 254 |
], |
| 255 |
key=lambda q: q["name"], |
| 256 |
) |
| 257 |
assert query_names_and_private == [ |
| 258 |
{"name": "add_name", "private": False}, |
| 259 |
{"name": "add_name_specify_id", "private": False}, |
| 260 |
{"name": "canned_read", "private": False}, |
| 261 |
{"name": "delete_name", "private": True}, |
| 262 |
{"name": "from_async_hook", "private": False}, |
| 263 |
{"name": "from_hook", "private": False}, |
| 264 |
{"name": "update_name", "private": False}, |
| 265 |
] |
| 266 |
|
| 267 |
|
| 268 |
def test_canned_query_permissions(canned_write_client): |
| 269 |
assert 403 == canned_write_client.get("/data/delete_name").status |
| 270 |
assert 200 == canned_write_client.get("/data/update_name").status |
| 271 |
cookies = {"ds_actor": canned_write_client.actor_cookie({"id": "root"})} |
| 272 |
assert 200 == canned_write_client.get("/data/delete_name", cookies=cookies).status |
| 273 |
assert 200 == canned_write_client.get("/data/update_name", cookies=cookies).status |
| 274 |
|
| 275 |
|
| 276 |
@pytest.fixture(scope="session") |
| 277 |
def magic_parameters_client(): |
| 278 |
with make_app_client( |
| 279 |
extra_databases={"data.db": "create table logs (line text)"}, |
| 280 |
metadata={ |
| 281 |
"databases": { |
| 282 |
"data": { |
| 283 |
"queries": { |
| 284 |
"runme_post": {"sql": "", "write": True}, |
| 285 |
"runme_get": {"sql": ""}, |
| 286 |
} |
| 287 |
} |
| 288 |
} |
| 289 |
}, |
| 290 |
) as client: |
| 291 |
yield client |
| 292 |
|
| 293 |
|
| 294 |
@pytest.mark.parametrize( |
| 295 |
"magic_parameter,expected_re", |
| 296 |
[ |
| 297 |
("_actor_id", "root"), |
| 298 |
("_header_host", "localhost"), |
| 299 |
("_header_not_a_thing", ""), |
| 300 |
("_cookie_foo", "bar"), |
| 301 |
("_now_epoch", r"^\d+$"), |
| 302 |
("_now_date_utc", r"^\d{4}-\d{2}-\d{2}$"), |
| 303 |
("_now_datetime_utc", r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$"), |
| 304 |
("_random_chars_1", r"^\w$"), |
| 305 |
("_random_chars_10", r"^\w{10}$"), |
| 306 |
], |
| 307 |
) |
| 308 |
def test_magic_parameters(magic_parameters_client, magic_parameter, expected_re): |
| 309 |
magic_parameters_client.ds._metadata["databases"]["data"]["queries"]["runme_post"][ |
| 310 |
"sql" |
| 311 |
] = f"insert into logs (line) values (:{magic_parameter})" |
| 312 |
magic_parameters_client.ds._metadata["databases"]["data"]["queries"]["runme_get"][ |
| 313 |
"sql" |
| 314 |
] = f"select :{magic_parameter} as result" |
| 315 |
cookies = { |
| 316 |
"ds_actor": magic_parameters_client.actor_cookie({"id": "root"}), |
| 317 |
"foo": "bar", |
| 318 |
} |
| 319 |
# Test the GET version |
| 320 |
get_response = magic_parameters_client.get( |
| 321 |
"/data/runme_get.json?_shape=array", cookies=cookies |
| 322 |
) |
| 323 |
get_actual = get_response.json[0]["result"] |
| 324 |
assert re.match(expected_re, str(get_actual)) |
| 325 |
# Test the form |
| 326 |
form_response = magic_parameters_client.get("/data/runme_post") |
| 327 |
soup = Soup(form_response.body, "html.parser") |
| 328 |
# The magic parameter should not be represented as a form field |
| 329 |
assert None is soup.find("input", {"name": magic_parameter}) |
| 330 |
# Submit the form to create a log line |
| 331 |
response = magic_parameters_client.post( |
| 332 |
"/data/runme_post?_json=1", {}, csrftoken_from=True, cookies=cookies |
| 333 |
) |
| 334 |
assert response.json == { |
| 335 |
"ok": True, |
| 336 |
"message": "Query executed, 1 row affected", |
| 337 |
"redirect": None, |
| 338 |
} |
| 339 |
post_actual = magic_parameters_client.get( |
| 340 |
"/data/logs.json?_sort_desc=rowid&_shape=array" |
| 341 |
).json[0]["line"] |
| 342 |
assert re.match(expected_re, post_actual) |
| 343 |
|
| 344 |
|
| 345 |
@pytest.mark.parametrize("use_csrf", [True, False]) |
| 346 |
@pytest.mark.parametrize("return_json", [True, False]) |
| 347 |
def test_magic_parameters_csrf_json(magic_parameters_client, use_csrf, return_json): |
| 348 |
magic_parameters_client.ds._metadata["databases"]["data"]["queries"]["runme_post"][ |
| 349 |
"sql" |
| 350 |
] = "insert into logs (line) values (:_header_host)" |
| 351 |
qs = "" |
| 352 |
if return_json: |
| 353 |
qs = "?_json=1" |
| 354 |
response = magic_parameters_client.post( |
| 355 |
f"/data/runme_post{qs}", |
| 356 |
{}, |
| 357 |
csrftoken_from=use_csrf or None, |
| 358 |
) |
| 359 |
if return_json: |
| 360 |
assert response.status == 200 |
| 361 |
assert response.json["ok"], response.json |
| 362 |
else: |
| 363 |
assert response.status == 302 |
| 364 |
messages = magic_parameters_client.ds.unsign( |
| 365 |
response.cookies["ds_messages"], "messages" |
| 366 |
) |
| 367 |
assert [["Query executed, 1 row affected", 1]] == messages |
| 368 |
post_actual = magic_parameters_client.get( |
| 369 |
"/data/logs.json?_sort_desc=rowid&_shape=array" |
| 370 |
).json[0]["line"] |
| 371 |
assert post_actual == "localhost" |
| 372 |
|
| 373 |
|
| 374 |
def test_magic_parameters_cannot_be_used_in_arbitrary_queries(magic_parameters_client): |
| 375 |
response = magic_parameters_client.get( |
| 376 |
"/data.json?sql=select+:_header_host&_shape=array" |
| 377 |
) |
| 378 |
assert 400 == response.status |
| 379 |
assert response.json["error"].startswith("You did not supply a value for binding") |
| 380 |
|
| 381 |
|
| 382 |
def test_canned_write_custom_template(canned_write_client): |
| 383 |
response = canned_write_client.get("/data/update_name") |
| 384 |
assert response.status == 200 |
| 385 |
assert ( |
| 386 |
"<!-- Templates considered: *query-data-update_name.html, query-data.html, query.html -->" |
| 387 |
in response.text |
| 388 |
) |
| 389 |
assert "!!!CUSTOM_UPDATE_NAME_TEMPLATE!!!" in response.text |
| 390 |
# And test for link rel=alternate while we're here: |
| 391 |
assert ( |
| 392 |
'<link rel="alternate" type="application/json+datasette" href="http://localhost/data/update_name.json">' |
| 393 |
in response.text |
| 394 |
) |
| 395 |
assert ( |
| 396 |
response.headers["link"] |
| 397 |
== 'http://localhost/data/update_name.json; rel="alternate"; type="application/json+datasette"' |
| 398 |
) |
| 399 |
|
| 400 |
|
| 401 |
def test_canned_write_query_disabled_for_immutable_database( |
| 402 |
canned_write_immutable_client, |
| 403 |
): |
| 404 |
response = canned_write_immutable_client.get("/fixtures/add") |
| 405 |
assert response.status == 200 |
| 406 |
assert ( |
| 407 |
"This query cannot be executed because the database is immutable." |
| 408 |
in response.text |
| 409 |
) |
| 410 |
assert '<input type="submit" value="Run SQL" disabled>' in response.text |
| 411 |
# Submitting form should get a forbidden error |
| 412 |
response = canned_write_immutable_client.post( |
| 413 |
"/fixtures/add", |
| 414 |
{"text": "text"}, |
| 415 |
csrftoken_from=True, |
| 416 |
) |
| 417 |
assert response.status == 403 |
| 418 |
assert "Database is immutable" in response.text |