BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / tests / pwa.py

pwa.py

fix: accept PATCH as a partial update for wiki pages and categories
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 5 weeks ago
f9b146ac History
pwa.py 11.1 KiB Download Raw
1#!/usr/bin/env python3
2"""Manifest, pictogrammen en service worker, met de juiste scope onder /verhaaltjesboek/."""
3import json
4import os
5import re
6import socket
7import struct
8import subprocess
9import tempfile
10import time
11import urllib.error
12import urllib.request
13from pathlib import Path
14
15WEB = Path(__file__).resolve().parents[1]
16ROOT = WEB.parent
17PREFIX = '/verhaaltjesboek'
18checks = 0
19
20def check(value, label):
21 global checks
22 checks += 1
23 assert value, label
24
25def png_size(path):
26 data = path.read_bytes()
27 check(data.startswith(b'\x89PNG\r\n\x1a\n') and data[12:16] == b'IHDR', f'{path.name} is een PNG')
28 return struct.unpack('>II', data[16:24])
29
30manifest = json.loads((WEB / 'manifest.webmanifest').read_text())
31check(manifest['name'] == 'Verhalenboek' and manifest['short_name'] == 'Verhalenboek', 'Naam van de webapp')
32check(manifest['lang'] == 'nl' and manifest['display'] == 'standalone', 'Taal en standalone-weergave')
33check(manifest['start_url'] == PREFIX + '/' and manifest['scope'] == PREFIX + '/', 'start_url en scope blijven in de submap')
34check(manifest['id'] == PREFIX + '/', 'App-id blijft de submap')
35check(manifest['start_url'].startswith(manifest['scope']), 'start_url valt binnen scope')
36check(manifest['theme_color'] == '#f4efe6' and manifest['background_color'] == '#f4efe6', 'Kleuren volgen de pagina')
37icons = {(icon['sizes'], icon['purpose']): icon for icon in manifest['icons']}
38for size, purpose in [('192x192', 'any'), ('512x512', 'any'), ('192x192', 'maskable'), ('512x512', 'maskable')]:
39 icon = icons.get((size, purpose))
40 check(icon is not None, f'Icoon {size} ({purpose})')
41 check(icon['src'].startswith(PREFIX + '/assets/'), f'Icoonpad blijft in de submap: {icon["src"]}')
42 file = WEB / icon['src'].removeprefix(PREFIX + '/')
43 check(file.is_file() and png_size(file) == tuple(int(part) for part in size.split('x')), f'{file.name} is {size}')
44
45check(png_size(WEB / 'assets/apple-touch-icon.png') == (180, 180), 'apple-touch-icon is 180')
46check(png_size(WEB / 'assets/favicon-32.png') == (32, 32), 'favicon-32 is 32')
47svg = (WEB / 'assets/favicon.svg').read_text()
48check('f4a261' in svg.lower() and '3f63d4' in svg.lower(), 'Favicon blijft een blauw boek met oranje bladwijzer')
49check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')
50
51worker = (WEB / 'sw.js').read_text()
52check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
53check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
54check('wiki' in worker and '/api.php/wiki/' in worker, 'Service worker noemt wiki-schrijfacties via api.php')
55check('PATCH' in worker and "request.method !== 'GET'" in worker, 'Service worker noemt PATCH en onderschept die methode niet')
56htaccess = (WEB / '.htaccess').read_text()
57check(re.search(r'(?i)<\s*/?\s*Limit', htaccess) is None, '.htaccess beperkt geen HTTP-methode')
58router_src = (WEB / 'router.php').read_text()
59check('REQUEST_METHOD' not in router_src, 'De ontwikkelrouter filtert geen HTTP-methode')
60wiki_bypass = re.compile(r'/(?:api|auth|callback)\.php(?:/|$)', re.I)
61check(wiki_bypass.search('/verhaaltjesboek/api.php/wiki/pages') and wiki_bypass.search('/verhaaltjesboek/api.php/wiki/categories'), 'Wiki-API valt onder de api.php-uitsluiting')
62check(worker.index("request.method !== 'GET'") < worker.index('function bypass'), 'Een schrijfactie komt niet in de cache terecht')
63check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
64registrar = (WEB / 'assets/pwa.js').read_text()
65check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
66
67router = r'''<?php
68declare(strict_types=1);
69$root = getenv('VERHALENBOEK_WEBROOT');
70$prefix = '/verhaaltjesboek';
71$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
72if ($path === $prefix) {
73 header('Location: '.$prefix.'/');
74 return true;
75}
76if (!is_string($root) || $root === '' || !str_starts_with($path, $prefix.'/')) {
77 http_response_code(404);
78 header('Content-Type: text/plain; charset=utf-8');
79 echo 'Niet gevonden';
80 return true;
81}
82$rel = substr($path, strlen($prefix));
83if (preg_match('#^/api\.php(?:/|$)#', $rel)) {
84 $_SERVER['SCRIPT_NAME'] = $prefix.'/api.php';
85 require $root.'/api.php';
86 return true;
87}
88if ($rel === '/' || $rel === '') {
89 $_SERVER['SCRIPT_NAME'] = $prefix.'/index.php';
90 require $root.'/index.php';
91 return true;
92}
93$file = $root.$rel;
94if (str_ends_with(strtolower($rel), '.php') && is_file($file)) {
95 $_SERVER['SCRIPT_NAME'] = $prefix.$rel;
96 require $file;
97 return true;
98}
99if (is_file($file)) {
100 $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
101 $type = match ($extension) {
102 'webmanifest' => 'application/manifest+json; charset=utf-8',
103 'js' => 'application/javascript; charset=utf-8',
104 'css' => 'text/css; charset=utf-8',
105 'svg' => 'image/svg+xml',
106 'png' => 'image/png',
107 default => 'application/octet-stream',
108 };
109 header('Content-Type: '.$type);
110 if ($extension === 'webmanifest' || basename($file) === 'sw.js') header('Cache-Control: no-cache');
111 readfile($file);
112 return true;
113}
114http_response_code(404);
115header('Content-Type: text/plain; charset=utf-8');
116echo 'Niet gevonden';
117return true;
118'''
119
120def free_port():
121 with socket.socket() as sock:
122 sock.bind(('127.0.0.1', 0))
123 return sock.getsockname()[1]
124
125def wait_for(url):
126 for _ in range(100):
127 try:
128 urllib.request.urlopen(url).close()
129 return
130 except urllib.error.URLError:
131 time.sleep(0.05)
132 raise RuntimeError('server startte niet: ' + url)
133
134def fetch(url, method='GET', data=None, headers=None):
135 request = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
136 try:
137 response = urllib.request.urlopen(request)
138 except urllib.error.HTTPError as error:
139 response = error
140 with response:
141 body = response.read()
142 return response.status, {key.lower(): value for key, value in response.headers.items()}, body
143
144with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as tmp:
145 tmp_path = Path(tmp)
146 (tmp_path / 'data').mkdir()
147 router_path = tmp_path / 'router.php'
148 router_path.write_text(router)
149 port = free_port()
150 base = f'http://127.0.0.1:{port}{PREFIX}'
151 log = (tmp_path / 'server.log').open('w')
152 process = subprocess.Popen(
153 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(tmp_path), str(router_path)],
154 stdout=log, stderr=log, start_new_session=True,
155 env={**os.environ, 'VERHALENBOEK_DATA_DIR': str(tmp_path / 'data'), 'VERHALENBOEK_WEBROOT': str(WEB)},
156 )
157 try:
158 wait_for(base + '/')
159 status, headers, body = fetch(base + '/manifest.webmanifest')
160 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Manifest heeft het juiste type')
161 served = json.loads(body)
162 check(served['start_url'] == PREFIX + '/' and served['scope'] == PREFIX + '/', 'Geserveerd manifest blijft in de submap')
163 status, headers, html = fetch(base + '/')
164 page = html.decode()
165 check(status == 200 and '<title>Verhalenboek</title>' in page, 'Startpagina onder de submap')
166 check('rel="manifest" href="manifest.webmanifest"' in page, 'Manifestlink is relatief')
167 check('href="/manifest' not in page and 'href="/assets/' not in page and 'src="/' not in page, 'Geen absolute paden vanaf de domeinwortel')
168 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
169 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
170 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
171 check(page.index('>Overzicht<') < page.index('>Wiki<') < page.index('>Instellingen<'), 'Wiki staat in het menu naast Overzicht')
172 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
173 status, headers, payload = fetch(base + '/assets/' + name)
174 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
175 status, headers, script = fetch(base + '/sw.js')
176 check(status == 200 and b"method !== 'GET'" in script and headers.get('content-type', '').startswith('application/javascript'), 'Service worker onder de submap')
177 status, _, me = fetch(base + '/api.php/me', headers={'Accept': 'application/json'})
178 profile = json.loads(me)
179 check(status == 200 and profile['user']['name'] == 'test_user_1', 'API GET onder de submap blijft werken')
180 status, _, denied = fetch(
181 base + '/api.php/days',
182 method='POST',
183 data=b'{}',
184 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
185 )
186 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
187 status, _, wiki_denied = fetch(
188 base + '/api.php/wiki/categories',
189 method='POST',
190 data=b'{"title":"Plekken"}',
191 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
192 )
193 check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_denied)['error'], 'Wiki-schrijven onder de submap blijft naar PHP gaan')
194 status, _, wiki_patch = fetch(
195 base + '/api.php/wiki/pages/oude-plein',
196 method='PATCH',
197 data=b'{"title":"Plein"}',
198 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
199 )
200 check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_patch)['error'], 'PATCH onder de submap bereikt PHP')
201 status, doc_headers, docs = fetch(base + '/docs.php')
202 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
203 finally:
204 process.kill()
205 process.wait(timeout=5)
206 log.close()
207
208root_port = free_port()
209with tempfile.TemporaryDirectory(prefix='pwa-root-', dir=WEB / 'tests/artifacts') as tmp:
210 env = {**os.environ, 'VERHALENBOEK_DATA_DIR': str(Path(tmp) / 'data')}
211 Path(tmp, 'data').mkdir()
212 log = Path(tmp, 'server.log').open('w')
213 process = subprocess.Popen(
214 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{root_port}', '-t', str(WEB), str(WEB / 'router.php')],
215 stdout=log, stderr=log, start_new_session=True, env=env,
216 )
217 try:
218 wait_for(f'http://127.0.0.1:{root_port}/')
219 status, headers, body = fetch(f'http://127.0.0.1:{root_port}/manifest.webmanifest')
220 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Lokale router zet het manifest-type')
221 check(b'"scope"' in body, 'Lokale router levert het manifest')
222 finally:
223 process.kill()
224 process.wait(timeout=5)
225 log.close()
226
227print(f'PWA: {checks} controles geslaagd.')