Debian Codegraph @

test/plugins/test_web.py

raw
1 """Tests for the 'web' plugin"""
2
3 import json
4 import platform
5 import shutil
6 from collections import Counter
7 from pathlib import Path
8
9 import pytest
10
11 from beets.library import Album, Item
12 from beets.test import _common
13 from beets.test.helper import PluginMixin, PytestTestHelper
14 from beetsplug import web
15
16
17 class WebPluginMixin(PluginMixin):
18 """Mixin to configure the web plugin for testing."""
19
20 plugin = "web"
21
22 @pytest.fixture(autouse=True)
23 def setup_web_app(self, setup):
24 """Configure the web plugin's Flask app for testing.
25
26 This fixture sets up the Flask test client and configures the app
27 with the test library. It runs after the base setup fixture from
28 PytestTestHelper.
29 """
30 # Set up the web app config - we modify self.config["web"] for beets config
31 # but also need to directly configure the Flask app for tests
32 web.app.config["TESTING"] = True
33 web.app.config["lib"] = self.lib
34 web.app.config["INCLUDE_PATHS"] = False
35 web.app.config["READONLY"] = True
36 self.client = web.app.test_client()
37
38 # Set platform-specific path prefix
39 self.path_prefix = Path(
40 "C:\\" if platform.system() == "Windows" else "/"
41 )
42
43 # Add library elements. Note that self.lib.add overrides any "id=<n>"
44 # and assigns the next free id number.
45 # The following adds will create items #1, #2 and #3
46 self.path1 = self.path_prefix / "path_1"
47 self.lib.add(
48 Item(
49 title="title", path=self.path1, album_id=2, artist="AAA Singers"
50 )
51 )
52 self.path2 = self.path_prefix / "somewhere" / "a"
53 self.lib.add(
54 Item(title="another title", path=self.path2, artist="AAA Singers")
55 )
56 self.path3 = self.path_prefix / "somewhere" / "abc"
57 self.lib.add(
58 Item(
59 title="and a third", testattr="ABC", path=self.path3, album_id=2
60 )
61 )
62 # The following adds will create albums #1 and #2
63 self.lib.add(Album(album="album", albumtest="xyz"))
64 self.path4 = self.path_prefix / "somewhere2" / "art_path_2"
65 self.lib.add(Album(album="other album", artpath=self.path4))
66
67 return
68
69
70 class TestWebPlugin(WebPluginMixin, PytestTestHelper):
71 """Tests for the web plugin."""
72
73 def test_config_include_paths_true(self):
74 web.app.config["INCLUDE_PATHS"] = True
75 response = self.client.get("/item/1")
76 res_json = json.loads(response.data.decode("utf-8"))
77 assert response.status_code == 200
78 assert res_json["path"] == str(self.path1)
79
80 web.app.config["INCLUDE_PATHS"] = False
81
82 def test_config_include_artpaths_true(self):
83 web.app.config["INCLUDE_PATHS"] = True
84 response = self.client.get("/album/2")
85 res_json = json.loads(response.data.decode("utf-8"))
86
87 assert response.status_code == 200
88 assert res_json["artpath"] == str(self.path4)
89
90 web.app.config["INCLUDE_PATHS"] = False
91
92 def test_config_include_paths_false(self):
93 web.app.config["INCLUDE_PATHS"] = False
94 response = self.client.get("/item/1")
95 res_json = json.loads(response.data.decode("utf-8"))
96
97 assert response.status_code == 200
98 assert "path" not in res_json
99
100 def test_config_include_artpaths_false(self):
101 web.app.config["INCLUDE_PATHS"] = False
102 response = self.client.get("/album/2")
103 res_json = json.loads(response.data.decode("utf-8"))
104
105 assert response.status_code == 200
106 assert "artpath" not in res_json
107
108 def test_get_all_items(self):
109 response = self.client.get("/item/")
110 res_json = json.loads(response.data.decode("utf-8"))
111
112 assert response.status_code == 200
113 assert len(res_json["items"]) == 3
114
115 def test_get_unique_item_artist(self):
116 response = self.client.get("/item/values/artist")
117 res_json = json.loads(response.data.decode("utf-8"))
118
119 assert response.status_code == 200
120 assert res_json["values"] == ["", "AAA Singers"]
121
122 def test_get_single_item_by_id(self):
123 response = self.client.get("/item/1")
124 res_json = json.loads(response.data.decode("utf-8"))
125
126 assert response.status_code == 200
127 assert res_json["id"] == 1
128 assert res_json["title"] == "title"
129
130 def test_get_multiple_items_by_id(self):
131 response = self.client.get("/item/1,2")
132 res_json = json.loads(response.data.decode("utf-8"))
133
134 assert response.status_code == 200
135 assert len(res_json["items"]) == 2
136 response_titles = {item["title"] for item in res_json["items"]}
137 assert response_titles == {"title", "another title"}
138
139 def test_get_single_item_not_found(self):
140 response = self.client.get("/item/4")
141 assert response.status_code == 404
142
143 def test_get_single_item_by_path(self):
144 data_path = _common.RSRC / "full.mp3"
145 self.lib.add(Item.from_path(data_path))
146 response = self.client.get(f"/item/path/{data_path}")
147 res_json = json.loads(response.data.decode("utf-8"))
148
149 assert response.status_code == 200
150 assert res_json["title"] == "full"
151
152 def test_get_single_item_by_path_not_found_if_not_in_library(self):
153 data_path = _common.RSRC / "full.mp3"
154 # data_path points to a valid file, but we have not added the file
155 # to the library.
156 response = self.client.get(f"/item/path/{data_path}")
157
158 assert response.status_code == 404
159
160 def test_get_item_empty_query(self):
161 response = self.client.get("/item/query/")
162 res_json = json.loads(response.data.decode("utf-8"))
163
164 assert response.status_code == 200
165 assert len(res_json["items"]) == 3
166
167 def test_get_simple_item_query(self):
168 response = self.client.get("/item/query/another")
169 res_json = json.loads(response.data.decode("utf-8"))
170
171 assert response.status_code == 200
172 assert len(res_json["results"]) == 1
173 assert res_json["results"][0]["title"] == "another title"
174
175 def test_query_item_string(self):
176 response = self.client.get("/item/query/testattr%3aABC") # testattr:ABC
177 res_json = json.loads(response.data.decode("utf-8"))
178
179 assert response.status_code == 200
180 assert len(res_json["results"]) == 1
181 assert res_json["results"][0]["title"] == "and a third"
182
183 def test_query_item_regex(self):
184 response = self.client.get(
185 "/item/query/testattr%3a%3a[A-C]%2b"
186 ) # testattr::[A-C]+
187 res_json = json.loads(response.data.decode("utf-8"))
188
189 assert response.status_code == 200
190 assert len(res_json["results"]) == 1
191 assert res_json["results"][0]["title"] == "and a third"
192
193 def test_query_item_regex_backslash(self):
194 response = self.client.get(
195 "/item/query/testattr%3a%3a%5cw%2b"
196 ) # testattr::\w+
197 res_json = json.loads(response.data.decode("utf-8"))
198
199 assert response.status_code == 200
200 assert len(res_json["results"]) == 1
201 assert res_json["results"][0]["title"] == "and a third"
202
203 def test_query_item_path(self):
204 """Note: path queries are special: the query item must match the path
205 from the root all the way to a directory, so this matches 1 item"""
206 """ Note: filesystem separators in the query must be '\' """
207
208 prefix = "C:" if platform.system() == "Windows" else ""
209 response = self.client.get(f"/item/query/path:{prefix}\\somewhere\\a")
210 res_json = json.loads(response.data.decode("utf-8"))
211
212 assert response.status_code == 200
213 assert len(res_json["results"]) == 1
214 assert res_json["results"][0]["title"] == "another title"
215
216 def test_get_all_albums(self):
217 response = self.client.get("/album/")
218 res_json = json.loads(response.data.decode("utf-8"))
219
220 assert response.status_code == 200
221 response_albums = [album["album"] for album in res_json["albums"]]
222 assert Counter(response_albums) == {"album": 1, "other album": 1}
223
224 def test_get_single_album_by_id(self):
225 response = self.client.get("/album/2")
226 res_json = json.loads(response.data.decode("utf-8"))
227
228 assert response.status_code == 200
229 assert res_json["id"] == 2
230 assert res_json["album"] == "other album"
231
232 def test_get_multiple_albums_by_id(self):
233 response = self.client.get("/album/1,2")
234 res_json = json.loads(response.data.decode("utf-8"))
235
236 assert response.status_code == 200
237 response_albums = [album["album"] for album in res_json["albums"]]
238 assert Counter(response_albums) == {"album": 1, "other album": 1}
239
240 def test_get_album_empty_query(self):
241 response = self.client.get("/album/query/")
242 res_json = json.loads(response.data.decode("utf-8"))
243
244 assert response.status_code == 200
245 assert len(res_json["albums"]) == 2
246
247 def test_get_simple_album_query(self):
248 response = self.client.get("/album/query/other")
249 res_json = json.loads(response.data.decode("utf-8"))
250
251 assert response.status_code == 200
252 assert len(res_json["results"]) == 1
253 assert res_json["results"][0]["album"] == "other album"
254 assert res_json["results"][0]["id"] == 2
255
256 def test_get_album_details(self):
257 response = self.client.get("/album/2?expand")
258 res_json = json.loads(response.data.decode("utf-8"))
259
260 assert response.status_code == 200
261 assert len(res_json["items"]) == 2
262 assert res_json["items"][0]["album"] == "other album"
263 assert res_json["items"][1]["album"] == "other album"
264 response_track_titles = {item["title"] for item in res_json["items"]}
265 assert response_track_titles == {"title", "and a third"}
266
267 def test_query_album_string(self):
268 response = self.client.get(
269 "/album/query/albumtest%3axy"
270 ) # albumtest:xy
271 res_json = json.loads(response.data.decode("utf-8"))
272
273 assert response.status_code == 200
274 assert len(res_json["results"]) == 1
275 assert res_json["results"][0]["album"] == "album"
276
277 def test_query_album_artpath_regex(self):
278 response = self.client.get(
279 "/album/query/artpath%3a%3aart_"
280 ) # artpath::art_
281 res_json = json.loads(response.data.decode("utf-8"))
282
283 assert response.status_code == 200
284 assert len(res_json["results"]) == 1
285 assert res_json["results"][0]["album"] == "other album"
286
287 def test_query_album_regex_backslash(self):
288 response = self.client.get(
289 "/album/query/albumtest%3a%3a%5cw%2b"
290 ) # albumtest::\w+
291 res_json = json.loads(response.data.decode("utf-8"))
292
293 assert response.status_code == 200
294 assert len(res_json["results"]) == 1
295 assert res_json["results"][0]["album"] == "album"
296
297 def test_get_stats(self):
298 response = self.client.get("/stats")
299 res_json = json.loads(response.data.decode("utf-8"))
300
301 assert response.status_code == 200
302 assert res_json["items"] == 3
303 assert res_json["albums"] == 2
304
305 def test_delete_item_id(self):
306 web.app.config["READONLY"] = False
307
308 # Create a temporary item
309 item_id = self.lib.add(
310 Item(title="test_delete_item_id", test_delete_item_id=1)
311 )
312
313 # Check we can find the temporary item we just created
314 response = self.client.get(f"/item/{item_id}")
315 res_json = json.loads(response.data.decode("utf-8"))
316 assert response.status_code == 200
317 assert res_json["id"] == item_id
318
319 # Delete item by id
320 response = self.client.delete(f"/item/{item_id}")
321 res_json = json.loads(response.data.decode("utf-8"))
322 assert response.status_code == 200
323
324 # Check the item has gone
325 response = self.client.get(f"/item/{item_id}")
326 assert response.status_code == 404
327 # Note: if this fails, the item may still be around
328 # and may cause other tests to fail
329
330 def test_delete_item_without_file(self):
331 web.app.config["READONLY"] = False
332
333 # Create an item with a file
334 ipath = self.temp_path / "testfile1.mp3"
335 shutil.copy(_common.RSRC / "full.mp3", ipath)
336 assert ipath.exists()
337 item_id = self.lib.add(Item.from_path(ipath))
338
339 # Check we can find the temporary item we just created
340 response = self.client.get(f"/item/{item_id}")
341 res_json = json.loads(response.data.decode("utf-8"))
342 assert response.status_code == 200
343 assert res_json["id"] == item_id
344
345 # Delete item by id, without deleting file
346 response = self.client.delete(f"/item/{item_id}")
347 res_json = json.loads(response.data.decode("utf-8"))
348 assert response.status_code == 200
349
350 # Check the item has gone
351 response = self.client.get(f"/item/{item_id}")
352 assert response.status_code == 404
353
354 # Check the file has not gone
355 assert ipath.exists()
356 ipath.unlink()
357
358 def test_delete_item_with_file(self):
359 web.app.config["READONLY"] = False
360
361 # Create an item with a file
362 ipath = self.temp_path / "testfile2.mp3"
363 shutil.copy(_common.RSRC / "full.mp3", ipath)
364 assert ipath.exists()
365 item_id = self.lib.add(Item.from_path(ipath))
366
367 # Check we can find the temporary item we just created
368 response = self.client.get(f"/item/{item_id}")
369 res_json = json.loads(response.data.decode("utf-8"))
370 assert response.status_code == 200
371 assert res_json["id"] == item_id
372
373 # Delete item by id, with file
374 response = self.client.delete(f"/item/{item_id}?delete")
375 res_json = json.loads(response.data.decode("utf-8"))
376 assert response.status_code == 200
377
378 # Check the item has gone
379 response = self.client.get(f"/item/{item_id}")
380 assert response.status_code == 404
381
382 # Check the file has gone
383 assert not ipath.exists()
384
385 def test_delete_item_query(self):
386 web.app.config["READONLY"] = False
387
388 # Create a temporary item
389 self.lib.add(
390 Item(title="test_delete_item_query", test_delete_item_query=1)
391 )
392
393 # Check we can find the temporary item we just created
394 response = self.client.get("/item/query/test_delete_item_query")
395 res_json = json.loads(response.data.decode("utf-8"))
396 assert response.status_code == 200
397 assert len(res_json["results"]) == 1
398
399 # Delete item by query
400 response = self.client.delete("/item/query/test_delete_item_query")
401 res_json = json.loads(response.data.decode("utf-8"))
402 assert response.status_code == 200
403
404 # Check the item has gone
405 response = self.client.get("/item/query/test_delete_item_query")
406 res_json = json.loads(response.data.decode("utf-8"))
407 assert response.status_code == 200
408 assert len(res_json["results"]) == 0
409
410 def test_delete_item_all_fails(self):
411 """DELETE is not supported for list all"""
412
413 web.app.config["READONLY"] = False
414
415 # Delete all items
416 response = self.client.delete("/item/")
417 assert response.status_code == 405
418
419 # Note: if this fails, all items have gone and rest of
420 # tests will fail!
421
422 def test_delete_item_id_readonly(self):
423 web.app.config["READONLY"] = True
424
425 # Create a temporary item
426 item_id = self.lib.add(
427 Item(title="test_delete_item_id_ro", test_delete_item_id_ro=1)
428 )
429
430 # Check we can find the temporary item we just created
431 response = self.client.get(f"/item/{item_id}")
432 res_json = json.loads(response.data.decode("utf-8"))
433 assert response.status_code == 200
434 assert res_json["id"] == item_id
435
436 # Try to delete item by id
437 response = self.client.delete(f"/item/{item_id}")
438 assert response.status_code == 405
439
440 # Check the item has not gone
441 response = self.client.get(f"/item/{item_id}")
442 res_json = json.loads(response.data.decode("utf-8"))
443 assert response.status_code == 200
444 assert res_json["id"] == item_id
445
446 # Remove it
447 self.lib.get_item(item_id).remove()
448
449 def test_delete_item_query_readonly(self):
450 web.app.config["READONLY"] = True
451
452 # Create a temporary item
453 item_id = self.lib.add(
454 Item(title="test_delete_item_q_ro", test_delete_item_q_ro=1)
455 )
456
457 # Check we can find the temporary item we just created
458 response = self.client.get("/item/query/test_delete_item_q_ro")
459 res_json = json.loads(response.data.decode("utf-8"))
460 assert response.status_code == 200
461 assert len(res_json["results"]) == 1
462
463 # Try to delete item by query
464 response = self.client.delete("/item/query/test_delete_item_q_ro")
465 assert response.status_code == 405
466
467 # Check the item has not gone
468 response = self.client.get("/item/query/test_delete_item_q_ro")
469 res_json = json.loads(response.data.decode("utf-8"))
470 assert response.status_code == 200
471 assert len(res_json["results"]) == 1
472
473 # Remove it
474 self.lib.get_item(item_id).remove()
475
476 def test_delete_album_id(self):
477 web.app.config["READONLY"] = False
478
479 # Create a temporary album
480 album_id = self.lib.add(
481 Album(album="test_delete_album_id", test_delete_album_id=1)
482 )
483
484 # Check we can find the temporary album we just created
485 response = self.client.get(f"/album/{album_id}")
486 res_json = json.loads(response.data.decode("utf-8"))
487 assert response.status_code == 200
488 assert res_json["id"] == album_id
489
490 # Delete album by id
491 response = self.client.delete(f"/album/{album_id}")
492 res_json = json.loads(response.data.decode("utf-8"))
493 assert response.status_code == 200
494
495 # Check the album has gone
496 response = self.client.get(f"/album/{album_id}")
497 assert response.status_code == 404
498 # Note: if this fails, the album may still be around
499 # and may cause other tests to fail
500
501 def test_delete_album_query(self):
502 web.app.config["READONLY"] = False
503
504 # Create a temporary album
505 self.lib.add(
506 Album(album="test_delete_album_query", test_delete_album_query=1)
507 )
508
509 # Check we can find the temporary album we just created
510 response = self.client.get("/album/query/test_delete_album_query")
511 res_json = json.loads(response.data.decode("utf-8"))
512 assert response.status_code == 200
513 assert len(res_json["results"]) == 1
514
515 # Delete album
516 response = self.client.delete("/album/query/test_delete_album_query")
517 res_json = json.loads(response.data.decode("utf-8"))
518 assert response.status_code == 200
519
520 # Check the album has gone
521 response = self.client.get("/album/query/test_delete_album_query")
522 res_json = json.loads(response.data.decode("utf-8"))
523 assert response.status_code == 200
524 assert len(res_json["results"]) == 0
525
526 def test_delete_album_all_fails(self):
527 """DELETE is not supported for list all"""
528
529 web.app.config["READONLY"] = False
530
531 # Delete all albums
532 response = self.client.delete("/album/")
533 assert response.status_code == 405
534
535 # Note: if this fails, all albums have gone and rest of
536 # tests will fail!
537
538 def test_delete_album_id_readonly(self):
539 web.app.config["READONLY"] = True
540
541 # Create a temporary album
542 album_id = self.lib.add(
543 Album(album="test_delete_album_id_ro", test_delete_album_id_ro=1)
544 )
545
546 # Check we can find the temporary album we just created
547 response = self.client.get(f"/album/{album_id}")
548 res_json = json.loads(response.data.decode("utf-8"))
549 assert response.status_code == 200
550 assert res_json["id"] == album_id
551
552 # Try to delete album by id
553 response = self.client.delete(f"/album/{album_id}")
554 assert response.status_code == 405
555
556 # Check the item has not gone
557 response = self.client.get(f"/album/{album_id}")
558 res_json = json.loads(response.data.decode("utf-8"))
559 assert response.status_code == 200
560 assert res_json["id"] == album_id
561
562 # Remove it
563 self.lib.get_album(album_id).remove()
564
565 def test_delete_album_query_readonly(self):
566 web.app.config["READONLY"] = True
567
568 # Create a temporary album
569 album_id = self.lib.add(
570 Album(
571 album="test_delete_album_query_ro", test_delete_album_query_ro=1
572 )
573 )
574
575 # Check we can find the temporary album we just created
576 response = self.client.get("/album/query/test_delete_album_query_ro")
577 res_json = json.loads(response.data.decode("utf-8"))
578 assert response.status_code == 200
579 assert len(res_json["results"]) == 1
580
581 # Try to delete album
582 response = self.client.delete("/album/query/test_delete_album_query_ro")
583 assert response.status_code == 405
584
585 # Check the album has not gone
586 response = self.client.get("/album/query/test_delete_album_query_ro")
587 res_json = json.loads(response.data.decode("utf-8"))
588 assert response.status_code == 200
589 assert len(res_json["results"]) == 1
590
591 # Remove it
592 self.lib.get_album(album_id).remove()
593
594 def test_patch_item_id(self):
595 # Note: PATCH is currently only implemented for track items, not albums
596
597 web.app.config["READONLY"] = False
598
599 # Create a temporary item
600 item_id = self.lib.add(
601 Item(
602 title="test_patch_item_id", test_patch_f1=1, test_patch_f2="Old"
603 )
604 )
605
606 # Check we can find the temporary item we just created
607 response = self.client.get(f"/item/{item_id}")
608 res_json = json.loads(response.data.decode("utf-8"))
609 assert response.status_code == 200
610 assert res_json["id"] == item_id
611 assert res_json["test_patch_f1"] == "1"
612 assert res_json["test_patch_f2"] == "Old"
613
614 # Patch item by id
615 # patch_json = json.JSONEncoder().encode({"test_patch_f2": "New"}]})
616 response = self.client.patch(
617 f"/item/{item_id}", json={"test_patch_f2": "New"}
618 )
619 res_json = json.loads(response.data.decode("utf-8"))
620 assert response.status_code == 200
621 assert res_json["id"] == item_id
622 assert res_json["test_patch_f1"] == "1"
623 assert res_json["test_patch_f2"] == "New"
624
625 # Check the update has really worked
626 response = self.client.get(f"/item/{item_id}")
627 res_json = json.loads(response.data.decode("utf-8"))
628 assert response.status_code == 200
629 assert res_json["id"] == item_id
630 assert res_json["test_patch_f1"] == "1"
631 assert res_json["test_patch_f2"] == "New"
632
633 # Remove the item
634 self.lib.get_item(item_id).remove()
635
636 def test_patch_item_id_readonly(self):
637 # Note: PATCH is currently only implemented for track items, not albums
638
639 web.app.config["READONLY"] = True
640
641 # Create a temporary item
642 item_id = self.lib.add(
643 Item(
644 title="test_patch_item_id_ro",
645 test_patch_f1=2,
646 test_patch_f2="Old",
647 )
648 )
649
650 # Check we can find the temporary item we just created
651 response = self.client.get(f"/item/{item_id}")
652 res_json = json.loads(response.data.decode("utf-8"))
653 assert response.status_code == 200
654 assert res_json["id"] == item_id
655 assert res_json["test_patch_f1"] == "2"
656 assert res_json["test_patch_f2"] == "Old"
657
658 # Patch item by id
659 # patch_json = json.JSONEncoder().encode({"test_patch_f2": "New"})
660 response = self.client.patch(
661 f"/item/{item_id}", json={"test_patch_f2": "New"}
662 )
663 assert response.status_code == 405
664
665 # Remove the item
666 self.lib.get_item(item_id).remove()
667
668 def test_get_item_file(self):
669 ipath = self.temp_path / "testfile2.mp3"
670 shutil.copy(_common.RSRC / "full.mp3", ipath)
671 assert ipath.exists()
672 item_id = self.lib.add(Item.from_path(ipath))
673
674 response = self.client.get(f"/item/{item_id}/file")
675
676 assert response.status_code == 200
677
678
679 class TestWebXSS(WebPluginMixin, PytestTestHelper):
680 """Tests for XSS vulnerability in the web plugin templates.
681
682 These tests verify that the Underscore.js templates in index.html use
683 the escaping syntax (<%- %) instead of the non-escaping syntax (<%= %).
684
685 In Underscore.js 1.2.2 (used by beets):
686 - <%= variable %> does NOT escape HTML (vulnerable to XSS)
687 - <%- variable %> DOES escape HTML (safe)
688
689 This was reported in
690 https://github.com/beetbox/beets/security/advisories/GHSA-3gxm-wfjx-m847
691 and remediated in
692 https://github.com/beetbox/beets/commit/75f0d8f4899e61afb939adf02dcfb078aed23a6a
693 """
694
695 def test_templates_use_escaping_syntax(self):
696 """Verify that all Underscore.js templates use <%- %> for escaping.
697
698 This test requests the index.html page and checks that all
699 user data interpolations in the Underscore.js templates use
700 the escaping syntax (<%- %) rather than the non-escaping syntax (<%= %).
701 """
702 import re
703
704 # Request the index.html page
705 response = self.client.get("/")
706 html = response.data.decode("utf-8")
707
708 # Extract the template scripts from the HTML
709 # The templates are in <script type="text/template"> blocks
710 template_pattern = r'<script type="text/template"[^>]*>(.*?)</script>'
711 templates = re.findall(template_pattern, html, re.DOTALL)
712
713 # Combine all template content for checking
714 all_template_content = "\n".join(templates)
715
716 # Check that no <%= %> (non-escaping) tags exist for user data
717 # We look for <%= followed by a variable name (word characters)
718 non_escaping_pattern = r"<%=\s*(\w+)\s*%>"
719 non_escaping_matches = re.findall(
720 non_escaping_pattern, all_template_content
721 )
722
723 # List of fields that should be escaped (user-controlled data)
724 user_data_fields = [
725 "title",
726 "artist",
727 "album",
728 "year",
729 "track",
730 "tracktotal",
731 "disc",
732 "disctotal",
733 "length",
734 "format",
735 "bitrate",
736 "mb_trackid",
737 "id",
738 "lyrics",
739 "comments",
740 ]
741
742 # Check if any user data fields are using non-escaping <%= %>
743 vulnerable_fields = [
744 field for field in non_escaping_matches if field in user_data_fields
745 ]
746
747 # If we found any user data fields using <%= %>, the templates are vulnerable
748 assert len(vulnerable_fields) == 0, (
749 "Found non-escaping <%= %> tags for user data fields: "
750 f"{vulnerable_fields}. "
751 "These should use <%- %> for HTML escaping to prevent XSS."
752 )
753
754 # Also verify that escaping tags (<%- %>) are present for user data
755 escaping_pattern = r"<%-\s*(\w+)\s*%>"
756 escaping_matches = re.findall(escaping_pattern, all_template_content)
757
758 # At least some user data fields should use escaping
759 safe_fields = [
760 field for field in escaping_matches if field in user_data_fields
761 ]
762 assert len(safe_fields) > 0, (
763 "No escaping <%- %> tags found for user data fields. "
764 "Templates should use <%- %> for HTML escaping."
765 )