Debian Codegraph @

tests/test_table_permissions.py

raw
1 import copy
2 import sqlite3
3
4 import pytest
5
6 from datasette import hookimpl
7 from datasette.app import Datasette
8 from datasette.plugins import pm
9
10
11 @pytest.mark.asyncio
12 @pytest.mark.parametrize("create_decoy", [False, True])
13 @pytest.mark.parametrize("path", [".json", "/1.json"])
14 async def test_trailing_lf_table_permissions(tmp_path, create_decoy, path):
15 db_path = tmp_path / "data.db"
16 conn = sqlite3.connect(db_path)
17 conn.executescript(
18 "create table secret (id integer primary key, value text);"
19 "insert into secret values (1, 'private');"
20 )
21 if create_decoy:
22 conn.executescript(
23 'create table "secret\n" (id integer primary key, value text);'
24 "insert into \"secret\n\" values (1, 'decoy');"
25 )
26 conn.close()
27 ds = Datasette(
28 [db_path],
29 settings={"default_allow_sql": False},
30 metadata={"databases": {"data": {"tables": {"secret": {"allow": False}}}}},
31 )
32 try:
33 response = await ds.client.get("/data.json?sql=select+*+from+secret")
34 assert response.status_code == 403
35 response = await ds.client.get("/data/secret" + path)
36 assert response.status_code == 403
37
38 # A trailing line feed must not bypass the protected table's permissions.
39 # Row URLs must also be safe when the suffixed table does not exist.
40 response = await ds.client.get("/data/secret~0A" + path + "?_shape=array")
41 if create_decoy:
42 assert response.status_code == 200, response.text
43 assert response.json() == [{"id": 1, "value": "decoy"}]
44 elif path == ".json":
45 assert response.status_code == 404
46 else:
47 assert response.status_code == 400
48 assert response.json()["error"] == "no such table: secret\n"
49 finally:
50 ds.executor.shutdown(wait=True)
51
52
53 @pytest.fixture
54 def ds(tmp_path):
55 path = tmp_path / "catalog.db"
56 with sqlite3.connect(path) as connection:
57 connection.executescript(
58 "create table Items (id integer primary key, label text);"
59 "insert into Items values (1, 'Example');"
60 "create view Report as select id, label from Items;"
61 'create table "Ärea" (id integer primary key);'
62 'create table "ärea" (id integer primary key);'
63 )
64 datasette = Datasette([path])
65 yield datasette
66 datasette.executor.shutdown(wait=True)
67
68
69 @pytest.fixture
70 def register_plugin():
71 plugins = []
72
73 def register(plugin):
74 pm.register(plugin)
75 plugins.append(plugin)
76 return plugin
77
78 yield register
79 for plugin in reversed(plugins):
80 pm.unregister(plugin)
81
82
83 @pytest.mark.asyncio
84 @pytest.mark.parametrize(
85 "requested,canonical",
86 [
87 ("Items", "Items"),
88 ("items", "Items"),
89 ("ITEMS", "Items"),
90 ("ItEmS", "Items"),
91 ("Report", "Report"),
92 ("report", "Report"),
93 ("REPORT", "Report"),
94 ("ÄREA", "Ärea"),
95 ("äREA", "ärea"),
96 ],
97 )
98 async def test_table_permission_hook_and_log_use_schema_spelling(
99 ds, register_plugin, requested, canonical
100 ):
101 calls = []
102
103 class Observer:
104 @hookimpl
105 def permission_allowed(self, action, resource):
106 calls.append((action, resource))
107
108 register_plugin(Observer())
109 assert await ds.permission_allowed(
110 None, "view-table", ("catalog", requested), default=True
111 )
112 assert calls == [("view-table", ("catalog", canonical))]
113 assert ds._permission_checks[-1]["resource"] == ("catalog", canonical)
114
115
116 @pytest.mark.asyncio
117 @pytest.mark.parametrize("name", ["items", "ITEMS", "report", "REPORT"])
118 async def test_table_allow_and_visibility_use_ascii_identity(ds, name):
119 ds._metadata_local = {
120 "databases": {
121 "catalog": {
122 "tables": {
123 "iTeMs": {"allow": {"id": "reader"}},
124 "rEpOrT": {"allow": {"id": "reader"}},
125 }
126 }
127 }
128 }
129 assert await ds.check_visibility(
130 {"id": "reader"}, "view-table", ("catalog", name)
131 ) == (True, True)
132
133
134 @pytest.mark.asyncio
135 @pytest.mark.parametrize("name,actor_id", [("ÄREA", "first"), ("äREA", "second")])
136 async def test_non_ascii_table_identities_remain_distinct(ds, name, actor_id):
137 ds._metadata_local = {
138 "databases": {
139 "catalog": {
140 "tables": {
141 "Ärea": {"allow": {"id": "first"}},
142 "ärea": {"allow": {"id": "second"}},
143 }
144 }
145 }
146 }
147 assert (
148 await ds.permission_allowed(
149 {"id": actor_id}, "view-table", ("catalog", name), default=None
150 )
151 is True
152 )
153 assert ds._table_permission_allows("catalog", name) == [{"id": actor_id}]
154
155
156 @pytest.mark.parametrize(
157 "plugin_name,local_name", [("Items", "ITEMS"), ("ITEMS", "Items")]
158 )
159 def test_local_metadata_precedence_across_table_spellings(
160 ds, register_plugin, plugin_name, local_name
161 ):
162 plugin_metadata = {
163 "databases": {
164 "catalog": {
165 "tables": {
166 plugin_name: {"allow": {"id": "plugin"}, "description": "Plugin"}
167 }
168 }
169 }
170 }
171 ds._metadata_local = {
172 "databases": {"catalog": {"tables": {local_name: {"allow": {"id": "local"}}}}}
173 }
174 original_plugin = copy.deepcopy(plugin_metadata)
175 original_local = copy.deepcopy(ds._metadata_local)
176 calls = []
177
178 class Metadata:
179 @hookimpl
180 def get_metadata(self, key, database, table):
181 calls.append((key, database, table))
182 return plugin_metadata
183
184 register_plugin(Metadata())
185 assert ds._table_permission_allows("catalog", "items") == [{"id": "local"}]
186 assert calls == [("tables", "catalog", None)]
187 assert plugin_metadata == original_plugin
188 assert ds._metadata_local == original_local
189 # The ordinary public metadata API keeps the configured spellings.
190 public_tables = ds.metadata("tables", database="catalog")
191 assert public_tables[plugin_name]["allow"] == {"id": "plugin"}
192 assert public_tables[local_name]["allow"] == {"id": "local"}
193
194
195 @pytest.mark.parametrize(
196 "local_tables,expected",
197 [
198 ({}, {"id": "reader"}),
199 ({"ITEMS": {"description": "Local"}}, {"id": "reader"}),
200 ({"ITEMS": {"allow": None}}, None),
201 ({"ITEMS": {"allow": {}}}, {"id": "reader"}),
202 (None, None),
203 ],
204 )
205 def test_legacy_nested_metadata_merge_is_preserved(
206 ds, register_plugin, local_tables, expected
207 ):
208 class Metadata:
209 @hookimpl
210 def get_metadata(self):
211 return {
212 "databases": {
213 "catalog": {"tables": {"Items": {"allow": {"id": "reader"}}}}
214 }
215 }
216
217 register_plugin(Metadata())
218 ds._metadata_local = {"databases": {"catalog": {"tables": local_tables}}}
219 assert ds._table_permission_allows("catalog", "Items") == (
220 [expected] if expected is not None else []
221 )
222
223
224 @pytest.mark.parametrize(
225 "database_metadata,expected",
226 [
227 ({}, {"id": "fallback"}),
228 ({"tables": {}}, None),
229 ({"tables": None}, None),
230 ({"tables": {"items": {"allow": {"id": "database"}}}}, {"id": "database"}),
231 ],
232 )
233 def test_existing_instance_table_metadata_fallback(ds, database_metadata, expected):
234 ds._metadata_local = {
235 "tables": {"ITEMS": {"allow": {"id": "fallback"}}},
236 "databases": {"catalog": database_metadata},
237 }
238 assert ds._table_permission_allows("catalog", "Items") == (
239 [expected] if expected is not None else []
240 )
241
242
243 @pytest.mark.asyncio
244 @pytest.mark.parametrize("reverse", [False, True])
245 @pytest.mark.parametrize("source", ["local", "plugin"])
246 @pytest.mark.parametrize("requested", ["Items", "ITEMS"])
247 async def test_same_source_case_variant_rules_use_deny_precedence(
248 ds, register_plugin, reverse, source, requested
249 ):
250 entries = [("Items", {"allow": {"id": "reader"}}), ("ITEMS", {"allow": {}})]
251 if reverse:
252 entries.reverse()
253 metadata = {"databases": {"catalog": {"tables": dict(entries)}}}
254 if source == "local":
255 ds._metadata_local = metadata
256 else:
257
258 class Metadata:
259 @hookimpl
260 def get_metadata(self):
261 return metadata
262
263 register_plugin(Metadata())
264 original = copy.deepcopy(metadata)
265 assert (
266 await ds.permission_allowed(
267 {"id": "reader"}, "view-table", ("catalog", requested), default=None
268 )
269 is False
270 )
271 assert metadata == original
272
273
274 @pytest.mark.asyncio
275 @pytest.mark.parametrize("reverse", [False, True])
276 async def test_local_allow_overlays_same_source_plugin_aliases(
277 ds, register_plugin, reverse
278 ):
279 entries = [
280 ("Items", {"allow": {"id": "first"}}),
281 ("ITEMS", {"allow": {"id": "second"}}),
282 ]
283 if reverse:
284 entries.reverse()
285
286 class Metadata:
287 @hookimpl
288 def get_metadata(self):
289 return {"databases": {"catalog": {"tables": dict(entries)}}}
290
291 register_plugin(Metadata())
292 ds._metadata_local = {
293 "databases": {"catalog": {"tables": {"items": {"allow": {"id": "local"}}}}}
294 }
295 assert ds._table_permission_allows("catalog", "Items") == [{"id": "local"}]
296 assert (
297 await ds.permission_allowed(
298 {"id": "local"}, "view-table", ("catalog", "Items"), default=None
299 )
300 is True
301 )
302
303
304 @pytest.mark.asyncio
305 async def test_plugin_permission_verdict_still_overrides_metadata(ds, register_plugin):
306 ds._metadata_local = {
307 "databases": {"catalog": {"tables": {"Items": {"allow": {"id": "reader"}}}}}
308 }
309
310 class Policy:
311 @hookimpl
312 def permission_allowed(self, action, resource):
313 if action == "view-table":
314 assert resource == ("catalog", "Items")
315 return False
316
317 register_plugin(Policy())
318 assert (
319 await ds.permission_allowed(
320 {"id": "reader"}, "view-table", ("catalog", "Items")
321 )
322 is False
323 )
324
325
326 @pytest.mark.asyncio
327 @pytest.mark.parametrize(
328 "action,resource",
329 [
330 ("view-database", "Catalog"),
331 ("execute-sql", "Catalog"),
332 ("no-match", ("catalog", "ITEMS")),
333 ("view-table", ("missing", "ITEMS")),
334 ("view-table", ("catalog", "FutureTable")),
335 ],
336 )
337 async def test_other_and_hypothetical_resources_keep_identity(
338 ds, register_plugin, action, resource
339 ):
340 calls = []
341
342 class Observer:
343 @hookimpl
344 def permission_allowed(self, action, resource):
345 calls.append((action, resource))
346
347 register_plugin(Observer())
348 assert await ds.permission_allowed(None, action, resource, default=True)
349 assert calls == [(action, resource)]
350
351
352 @pytest.mark.asyncio
353 async def test_canned_query_names_remain_case_sensitive(ds, register_plugin):
354 ds._metadata_local = {
355 "databases": {
356 "catalog": {
357 "queries": {
358 "Report": {"sql": "select 1", "allow": {"id": "first"}},
359 "report": {"sql": "select 2", "allow": {"id": "second"}},
360 }
361 }
362 }
363 }
364 for name, actor_id in (("Report", "first"), ("report", "second")):
365 assert (
366 await ds.permission_allowed(
367 {"id": actor_id}, "view-query", ("catalog", name), default=None
368 )
369 is True
370 )
371 assert ds._permission_checks[-1]["resource"] == ("catalog", name)
372
373
374 @pytest.mark.asyncio
375 @pytest.mark.parametrize(
376 "path",
377 [
378 "/catalog",
379 "/catalog/Items.json",
380 "/catalog/Report.json",
381 "/catalog/Items/1.json",
382 ],
383 )
384 async def test_ordinary_requests_retain_table_permission_hooks(
385 ds, register_plugin, path
386 ):
387 calls = []
388
389 class Observer:
390 @hookimpl
391 def permission_allowed(self, action, resource):
392 if action == "view-table":
393 calls.append(resource)
394
395 register_plugin(Observer())
396 response = await ds.client.get(path)
397 assert response.status_code == 200
398 assert calls
399 assert all(
400 database == "catalog" and name in {"Items", "Report", "Ärea", "ärea"}
401 for database, name in calls
402 )