Debian Codegraph @

tests/test_permissions.py

raw
1 from .fixtures import app_client, assert_permissions_checked, make_app_client
2 from bs4 import BeautifulSoup as Soup
3 import copy
4 import pytest
5 import urllib
6
7
8 @pytest.fixture(scope="module")
9 def padlock_client():
10 with make_app_client(
11 metadata={
12 "databases": {
13 "fixtures": {
14 "queries": {"two": {"sql": "select 1 + 1"}},
15 }
16 }
17 }
18 ) as client:
19 yield client
20
21
22 @pytest.mark.parametrize(
23 "allow,expected_anon,expected_auth",
24 [
25 (None, 200, 200),
26 ({}, 403, 403),
27 ({"id": "root"}, 403, 200),
28 ],
29 )
30 @pytest.mark.parametrize(
31 "path",
32 (
33 "/",
34 "/fixtures",
35 "/fixtures/compound_three_primary_keys",
36 "/fixtures/compound_three_primary_keys/a,a,a",
37 "/fixtures/two", # Query
38 ),
39 )
40 def test_view_padlock(allow, expected_anon, expected_auth, path, padlock_client):
41 padlock_client.ds._metadata_local["allow"] = allow
42 fragment = "🔒</h1>"
43 anon_response = padlock_client.get(path)
44 assert expected_anon == anon_response.status
45 if allow and anon_response.status == 200:
46 # Should be no padlock
47 assert fragment not in anon_response.text
48 auth_response = padlock_client.get(
49 path,
50 cookies={"ds_actor": padlock_client.actor_cookie({"id": "root"})},
51 )
52 assert expected_auth == auth_response.status
53 # Check for the padlock
54 if allow and expected_anon == 403 and expected_auth == 200:
55 assert fragment in auth_response.text
56 del padlock_client.ds._metadata_local["allow"]
57
58
59 @pytest.mark.parametrize(
60 "allow,expected_anon,expected_auth",
61 [
62 (None, 200, 200),
63 ({}, 403, 403),
64 ({"id": "root"}, 403, 200),
65 ],
66 )
67 def test_view_database(allow, expected_anon, expected_auth):
68 with make_app_client(
69 metadata={"databases": {"fixtures": {"allow": allow}}}
70 ) as client:
71 for path in (
72 "/fixtures",
73 "/fixtures/compound_three_primary_keys",
74 "/fixtures/compound_three_primary_keys/a,a,a",
75 ):
76 anon_response = client.get(path)
77 assert expected_anon == anon_response.status, path
78 if allow and path == "/fixtures" and anon_response.status == 200:
79 # Should be no padlock
80 assert ">fixtures 🔒</h1>" not in anon_response.text
81 auth_response = client.get(
82 path,
83 cookies={"ds_actor": client.actor_cookie({"id": "root"})},
84 )
85 assert expected_auth == auth_response.status
86 if (
87 allow
88 and path == "/fixtures"
89 and expected_anon == 403
90 and expected_auth == 200
91 ):
92 assert ">fixtures 🔒</h1>" in auth_response.text
93
94
95 def test_database_list_respects_view_database():
96 with make_app_client(
97 metadata={"databases": {"fixtures": {"allow": {"id": "root"}}}},
98 extra_databases={"data.db": "create table names (name text)"},
99 ) as client:
100 anon_response = client.get("/")
101 assert '<a href="/data">data</a></h2>' in anon_response.text
102 assert '<a href="/fixtures">fixtures</a>' not in anon_response.text
103 auth_response = client.get(
104 "/",
105 cookies={"ds_actor": client.actor_cookie({"id": "root"})},
106 )
107 assert '<a href="/data">data</a></h2>' in auth_response.text
108 assert '<a href="/fixtures">fixtures</a> 🔒</h2>' in auth_response.text
109
110
111 def test_database_list_respects_view_table():
112 with make_app_client(
113 metadata={
114 "databases": {
115 "data": {
116 "tables": {
117 "names": {"allow": {"id": "root"}},
118 "v": {"allow": {"id": "root"}},
119 }
120 }
121 }
122 },
123 extra_databases={
124 "data.db": "create table names (name text); create view v as select * from names"
125 },
126 ) as client:
127 html_fragments = [
128 ">names</a> 🔒",
129 ">v</a> 🔒",
130 ]
131 anon_response_text = client.get("/").text
132 assert "0 rows in 0 tables" in anon_response_text
133 for html_fragment in html_fragments:
134 assert html_fragment not in anon_response_text
135 auth_response_text = client.get(
136 "/",
137 cookies={"ds_actor": client.actor_cookie({"id": "root"})},
138 ).text
139 for html_fragment in html_fragments:
140 assert html_fragment in auth_response_text
141
142
143 @pytest.mark.parametrize(
144 "allow,expected_anon,expected_auth",
145 [
146 (None, 200, 200),
147 ({}, 403, 403),
148 ({"id": "root"}, 403, 200),
149 ],
150 )
151 def test_view_table(allow, expected_anon, expected_auth):
152 with make_app_client(
153 metadata={
154 "databases": {
155 "fixtures": {
156 "tables": {"compound_three_primary_keys": {"allow": allow}}
157 }
158 }
159 }
160 ) as client:
161 anon_response = client.get("/fixtures/compound_three_primary_keys")
162 assert expected_anon == anon_response.status
163 if allow and anon_response.status == 200:
164 # Should be no padlock
165 assert ">compound_three_primary_keys 🔒</h1>" not in anon_response.text
166 auth_response = client.get(
167 "/fixtures/compound_three_primary_keys",
168 cookies={"ds_actor": client.actor_cookie({"id": "root"})},
169 )
170 assert expected_auth == auth_response.status
171 if allow and expected_anon == 403 and expected_auth == 200:
172 assert ">compound_three_primary_keys 🔒</h1>" in auth_response.text
173
174
175 def test_table_list_respects_view_table():
176 with make_app_client(
177 metadata={
178 "databases": {
179 "fixtures": {
180 "tables": {
181 "compound_three_primary_keys": {"allow": {"id": "root"}},
182 # And a SQL view too:
183 "paginated_view": {"allow": {"id": "root"}},
184 }
185 }
186 }
187 }
188 ) as client:
189 html_fragments = [
190 ">compound_three_primary_keys</a> 🔒",
191 ">paginated_view</a> 🔒",
192 ]
193 anon_response = client.get("/fixtures")
194 for html_fragment in html_fragments:
195 assert html_fragment not in anon_response.text
196 auth_response = client.get(
197 "/fixtures", cookies={"ds_actor": client.actor_cookie({"id": "root"})}
198 )
199 for html_fragment in html_fragments:
200 assert html_fragment in auth_response.text
201
202
203 @pytest.mark.parametrize(
204 "allow,expected_anon,expected_auth",
205 [
206 (None, 200, 200),
207 ({}, 403, 403),
208 ({"id": "root"}, 403, 200),
209 ],
210 )
211 def test_view_query(allow, expected_anon, expected_auth):
212 with make_app_client(
213 metadata={
214 "databases": {
215 "fixtures": {"queries": {"q": {"sql": "select 1 + 1", "allow": allow}}}
216 }
217 }
218 ) as client:
219 anon_response = client.get("/fixtures/q")
220 assert expected_anon == anon_response.status
221 if allow and anon_response.status == 200:
222 # Should be no padlock
223 assert "🔒</h1>" not in anon_response.text
224 auth_response = client.get(
225 "/fixtures/q", cookies={"ds_actor": client.actor_cookie({"id": "root"})}
226 )
227 assert expected_auth == auth_response.status
228 if allow and expected_anon == 403 and expected_auth == 200:
229 assert ">fixtures: q 🔒</h1>" in auth_response.text
230
231
232 @pytest.mark.parametrize(
233 "metadata",
234 [
235 {"allow_sql": {"id": "root"}},
236 {"databases": {"fixtures": {"allow_sql": {"id": "root"}}}},
237 ],
238 )
239 def test_execute_sql(metadata):
240 with make_app_client(metadata=metadata) as client:
241 form_fragment = '<form class="sql" action="/fixtures"'
242
243 # Anonymous users - should not display the form:
244 assert form_fragment not in client.get("/fixtures").text
245 # This should 403:
246 assert 403 == client.get("/fixtures?sql=select+1").status
247 # ?_where= not allowed on tables:
248 assert 403 == client.get("/fixtures/facet_cities?_where=id=3").status
249
250 # But for logged in user all of these should work:
251 cookies = {"ds_actor": client.actor_cookie({"id": "root"})}
252 response_text = client.get("/fixtures", cookies=cookies).text
253 assert form_fragment in response_text
254 assert 200 == client.get("/fixtures?sql=select+1", cookies=cookies).status
255 assert (
256 200
257 == client.get("/fixtures/facet_cities?_where=id=3", cookies=cookies).status
258 )
259
260
261 def test_query_list_respects_view_query():
262 with make_app_client(
263 metadata={
264 "databases": {
265 "fixtures": {
266 "queries": {"q": {"sql": "select 1 + 1", "allow": {"id": "root"}}}
267 }
268 }
269 }
270 ) as client:
271 html_fragment = '<li><a href="/fixtures/q" title="select 1 + 1">q</a> 🔒</li>'
272 anon_response = client.get("/fixtures")
273 assert html_fragment not in anon_response.text
274 assert '"/fixtures/q"' not in anon_response.text
275 auth_response = client.get(
276 "/fixtures", cookies={"ds_actor": client.actor_cookie({"id": "root"})}
277 )
278 assert html_fragment in auth_response.text
279
280
281 @pytest.mark.parametrize(
282 "path,permissions",
283 [
284 ("/", ["view-instance"]),
285 ("/fixtures", ["view-instance", ("view-database", "fixtures")]),
286 (
287 "/fixtures/facetable/1",
288 ["view-instance", ("view-table", ("fixtures", "facetable"))],
289 ),
290 (
291 "/fixtures/simple_primary_key",
292 [
293 "view-instance",
294 ("view-database", "fixtures"),
295 ("view-table", ("fixtures", "simple_primary_key")),
296 ],
297 ),
298 (
299 "/fixtures?sql=select+1",
300 [
301 "view-instance",
302 ("view-database", "fixtures"),
303 ("execute-sql", "fixtures"),
304 ],
305 ),
306 (
307 "/fixtures.db",
308 [
309 "view-instance",
310 ("view-database", "fixtures"),
311 ("view-database-download", "fixtures"),
312 ],
313 ),
314 (
315 "/fixtures/neighborhood_search",
316 [
317 "view-instance",
318 ("view-database", "fixtures"),
319 ("view-query", ("fixtures", "neighborhood_search")),
320 ],
321 ),
322 ],
323 )
324 def test_permissions_checked(app_client, path, permissions):
325 app_client.ds._permission_checks.clear()
326 response = app_client.get(path)
327 assert response.status in (200, 403)
328 assert_permissions_checked(app_client.ds, permissions)
329
330
331 def test_permissions_debug(app_client):
332 app_client.ds._permission_checks.clear()
333 assert app_client.get("/-/permissions").status == 403
334 # With the cookie it should work
335 cookie = app_client.actor_cookie({"id": "root"})
336 response = app_client.get("/-/permissions", cookies={"ds_actor": cookie})
337 assert response.status == 200
338 # Should show one failure and one success
339 soup = Soup(response.body, "html.parser")
340 check_divs = soup.find_all("div", {"class": "check"})
341 checks = [
342 {
343 "action": div.select_one(".check-action").text,
344 # True = green tick, False = red cross, None = gray None
345 "result": (
346 None
347 if div.select(".check-result-no-opinion")
348 else bool(div.select(".check-result-true"))
349 ),
350 "used_default": bool(div.select(".check-used-default")),
351 }
352 for div in check_divs
353 ]
354 assert checks == [
355 {"action": "permissions-debug", "result": True, "used_default": False},
356 {"action": "view-instance", "result": None, "used_default": True},
357 {"action": "debug-menu", "result": False, "used_default": True},
358 {"action": "view-instance", "result": True, "used_default": True},
359 {"action": "permissions-debug", "result": False, "used_default": True},
360 {"action": "view-instance", "result": None, "used_default": True},
361 ]
362
363
364 @pytest.mark.parametrize(
365 "actor,allow,expected_fragment",
366 [
367 ('{"id":"root"}', "{}", "Result: deny"),
368 ('{"id":"root"}', '{"id": "*"}', "Result: allow"),
369 ('{"', '{"id": "*"}', "Actor JSON error"),
370 ('{"id":"root"}', '"*"}', "Allow JSON error"),
371 ],
372 )
373 def test_allow_debug(app_client, actor, allow, expected_fragment):
374 response = app_client.get(
375 "/-/allow-debug?" + urllib.parse.urlencode({"actor": actor, "allow": allow})
376 )
377 assert 200 == response.status
378 assert expected_fragment in response.text
379
380
381 @pytest.mark.parametrize(
382 "allow,expected",
383 [
384 ({"id": "root"}, 403),
385 ({"id": "root", "unauthenticated": True}, 200),
386 ],
387 )
388 def test_allow_unauthenticated(allow, expected):
389 with make_app_client(metadata={"allow": allow}) as client:
390 assert expected == client.get("/").status
391
392
393 @pytest.fixture(scope="session")
394 def view_instance_client():
395 with make_app_client(metadata={"allow": {}}) as client:
396 yield client
397
398
399 @pytest.mark.parametrize(
400 "path",
401 [
402 "/",
403 "/fixtures",
404 "/fixtures/facetable",
405 "/-/metadata",
406 "/-/versions",
407 "/-/plugins",
408 "/-/settings",
409 "/-/threads",
410 "/-/databases",
411 "/-/actor",
412 "/-/permissions",
413 "/-/messages",
414 "/-/patterns",
415 ],
416 )
417 def test_view_instance(path, view_instance_client):
418 assert 403 == view_instance_client.get(path).status
419 if path not in ("/-/permissions", "/-/messages", "/-/patterns"):
420 assert 403 == view_instance_client.get(path + ".json").status
421
422
423 @pytest.fixture(scope="session")
424 def cascade_app_client():
425 with make_app_client(is_immutable=True) as client:
426 yield client
427
428
429 @pytest.mark.parametrize(
430 "path,permissions,expected_status",
431 [
432 ("/", [], 403),
433 ("/", ["instance"], 200),
434 # Can view table even if not allowed database or instance
435 ("/fixtures/binary_data", [], 403),
436 ("/fixtures/binary_data", ["database"], 403),
437 ("/fixtures/binary_data", ["instance"], 403),
438 ("/fixtures/binary_data", ["table"], 200),
439 ("/fixtures/binary_data", ["table", "database"], 200),
440 ("/fixtures/binary_data", ["table", "database", "instance"], 200),
441 # ... same for row
442 ("/fixtures/binary_data/1", [], 403),
443 ("/fixtures/binary_data/1", ["database"], 403),
444 ("/fixtures/binary_data/1", ["instance"], 403),
445 ("/fixtures/binary_data/1", ["table"], 200),
446 ("/fixtures/binary_data/1", ["table", "database"], 200),
447 ("/fixtures/binary_data/1", ["table", "database", "instance"], 200),
448 # Can view query even if not allowed database or instance
449 ("/fixtures/magic_parameters", [], 403),
450 ("/fixtures/magic_parameters", ["database"], 403),
451 ("/fixtures/magic_parameters", ["instance"], 403),
452 ("/fixtures/magic_parameters", ["query"], 200),
453 ("/fixtures/magic_parameters", ["query", "database"], 200),
454 ("/fixtures/magic_parameters", ["query", "database", "instance"], 200),
455 # Can view database even if not allowed instance
456 ("/fixtures", [], 403),
457 ("/fixtures", ["instance"], 403),
458 ("/fixtures", ["database"], 200),
459 # Downloading the fixtures.db file
460 ("/fixtures.db", [], 403),
461 ("/fixtures.db", ["instance"], 403),
462 ("/fixtures.db", ["database"], 200),
463 ("/fixtures.db", ["download"], 200),
464 ],
465 )
466 def test_permissions_cascade(cascade_app_client, path, permissions, expected_status):
467 """Test that e.g. having view-table but NOT view-database lets you view table page, etc"""
468 allow = {"id": "*"}
469 deny = {}
470 previous_metadata = cascade_app_client.ds.metadata()
471 updated_metadata = copy.deepcopy(previous_metadata)
472 actor = {"id": "test"}
473 if "download" in permissions:
474 actor["can_download"] = 1
475 try:
476 # Set up the different allow blocks
477 updated_metadata["allow"] = allow if "instance" in permissions else deny
478 updated_metadata["databases"]["fixtures"]["allow"] = (
479 allow if "database" in permissions else deny
480 )
481 updated_metadata["databases"]["fixtures"]["tables"]["binary_data"] = {
482 "allow": (allow if "table" in permissions else deny)
483 }
484 updated_metadata["databases"]["fixtures"]["queries"]["magic_parameters"][
485 "allow"
486 ] = (allow if "query" in permissions else deny)
487 cascade_app_client.ds._metadata_local = updated_metadata
488 response = cascade_app_client.get(
489 path,
490 cookies={"ds_actor": cascade_app_client.actor_cookie(actor)},
491 )
492 assert (
493 response.status == expected_status
494 ), "path: {}, permissions: {}, expected_status: {}, status: {}".format(
495 path, permissions, expected_status, response.status
496 )
497 finally:
498 cascade_app_client.ds._metadata_local = previous_metadata
499
500
501 def test_padlocks_on_database_page(cascade_app_client):
502 metadata = {
503 "databases": {
504 "fixtures": {
505 "allow": {"id": "test"},
506 "tables": {
507 "123_starts_with_digits": {"allow": True},
508 "simple_view": {"allow": True},
509 },
510 "queries": {"query_two": {"allow": True, "sql": "select 2"}},
511 }
512 }
513 }
514 previous_metadata = cascade_app_client.ds._metadata_local
515 try:
516 cascade_app_client.ds._metadata_local = metadata
517 response = cascade_app_client.get(
518 "/fixtures",
519 cookies={"ds_actor": cascade_app_client.actor_cookie({"id": "test"})},
520 )
521 # Tables
522 assert ">123_starts_with_digits</a></h3>" in response.text
523 assert ">Table With Space In Name</a> 🔒</h3>" in response.text
524 # Queries
525 assert ">from_async_hook</a> 🔒</li>" in response.text
526 assert ">query_two</a></li>" in response.text
527 # Views
528 assert ">paginated_view</a> 🔒</li>" in response.text
529 assert ">simple_view</a></li>" in response.text
530 finally:
531 cascade_app_client.ds._metadata_local = previous_metadata