repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

303 lines · 34.0 KB · download this file

#!/usr/bin/env python3
"""Comments, likes, sharing and the theme editor, on a new site's catalogue (never the
site's own). Never touches live data, credentials or media."""
import sys,pathlib;sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import start_catalog
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets
import html as H
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent));import signin  # signs requests in (REMOTE_USER → session cookie)
script=str(pathlib.Path(sys.argv[1]).resolve())
checks=[]
def check(v,msg):
 assert v,msg
 checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-engagement-test-') as tmp:
 root=pathlib.Path(tmp);data=root/'var/db/blowfishcms';(data/'admin/tmp').mkdir(parents=True)
 (data/'admin/csrf.key').write_text(secrets.token_hex(32))
 for kind in ['photography','music','artwork','blog']:(root/'media/blowfishcms'/kind).mkdir(parents=True)
 copied_uploads=start_catalog(data/'catalog.sqlite')
 # Start from a known state: a new site's catalogue, with its pages rebuilt
 # from the original seed by the migration below.
 with signin.connect(data/'catalog.sqlite') as copy:
  for table in ['themes','site_settings','links','pages','page_blocks']:copy.execute('drop table if exists '+table)
 env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json'),'BLOWFISH_THEMES_PATH':str(pathlib.Path(__file__).resolve().parent/'fixtures/themes')}
 def run(path,fields=None,cookie='',user='',ip='192.0.2.1',origin='https://example.net',fetch=False):
  url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {},doseq=True).encode() if fields is not None else b''
  e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':url.path,'QUERY_STRING':url.query,
     'CONTENT_TYPE':'application/x-www-form-urlencoded','CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':cookie,'REMOTE_USER':user,'HTTP_ORIGIN':origin,'REMOTE_ADDR':ip}
  if fetch:e['HTTP_X_REQUESTED_WITH']='fetch'
  p=subprocess.run(['perl',script],input=body,env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  assert p.returncode==0,(p.stderr.decode(),p.stdout[:300])
  head,html=p.stdout.decode().split('\r\n\r\n',1);hdr={}
  for line in head.split('\r\n'):k,v=line.split(': ',1);hdr[k]=v
  return int(hdr['Status']),html,hdr
 def picker(html):
  m=re.search(r'<select id="theme-picker"[^>]*>(.*?)</select>',html,re.S);return re.findall(r'<option value="([^"]*)"',m.group(1)) if m else []
 def cookie_of(hdr,name):
  m=re.match(name+r'=([^;]+)',hdr.get('Set-Cookie',''));return m.group(1) if m else ''

 subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.DEVNULL)
 con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
 check([(r['slug'],r['enabled'],r['package']) for r in con.execute('select * from themes order by sort_order')]==[('modern',1,'modern'),('modern-dark',1,'modern'),('sample',0,'sample'),('sample-light',0,'sample')],'migration adds Modern, shown, then installed themes’ variants, hidden')
 con.execute("delete from themes where slug='sample-light'");con.commit();subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
 check(con.execute("select count(*) from themes where slug='sample-light'").fetchone()[0]==0,'a deleted variant is not brought back')
 status,css,hdr=run('/themes.css');check(status==200 and hdr['Content-Type'].startswith('text/css'),'theme stylesheet served')
 check('data-theme="modern-dark"' in css and 'data-theme="sample"' not in css,'visitors get only the variants they can have, not hidden ones')
 html=run('/?theme=sample')[1];m=re.search(r'href="/themes\.css\?v=([0-9a-f]+)&amp;with=sample"',html)
 status,css,hdr=run('/themes.css?v='+(m.group(1) if m else 'x')+'&with=sample')
 check(m and 'immutable' in hdr['Cache-Control'] and ':root[data-theme="sample"]' in css,'previewing a hidden variant (?theme=) loads it as well')
 check(':root[data-theme="sample"]{color-scheme:dark;' in css and '--bg:#15151f' in css,'variant colours generated')
 check(':root[data-theme="sample"] .window__bar,:root[data-theme="sample"] :is(h1,h2){' in css and ':root[data-theme="sample"]{ --x: 1 }' in css and '@media (max-width:600px){:root[data-theme="sample"] body{' in css,'a theme’s CSS is limited to its variants, including :root and @media')
 check(re.search(r':root\[data-theme="modern-dark"\] [^{]+\{',css) and 'data-theme="broken"' not in css and 'data-theme="future"' not in css,'Modern is drawn from its folder; themes that can’t be used add nothing')
 version=re.search(r'href="/themes\.css\?v=([0-9a-f]+)"',run('/')[1]).group(1)
 check('immutable' in run('/themes.css?v='+version)[2]['Cache-Control'] and 'no-cache' in run('/themes.css?v=old')[2]['Cache-Control'],'theme stylesheet cached only for the current version')
 for page in ['/','/projects/','/resume/','/contact/','/blog/','/photography/']:
  html=run(page)[1]
  check('<link rel="stylesheet" href="/themes.css?v=' in html and picker(html)==['modern'] and 'data-variants="modern modern-dark"' in html and 'name="site-themes"' in html,'theme picker (one entry per theme) and stylesheet on '+page)
  check('id="theme-mode"' in html and '"pair":"modern-dark"' in html.replace('&quot;','"') and '"pair":"modern"' in html.replace('&quot;','"'),'a light/dark switch beside it, with each variant’s other-scheme twin for theme.js on '+page)
 check('<!--EDIT:section_2-->' not in run('/contact/')[1],'contact page theme picker restored')
 listing=subprocess.run(['perl',script,'--themes'],env=env,capture_output=True,text=True).stdout
 modern=json.loads((pathlib.Path(__file__).resolve().parent.parent/'themes/modern/theme.json').read_text())['version']
 check(f'modern\t{modern}\tcore\tok' in listing and 'sample\t1.0.0\tinstalled\tok' in listing and 'needs BlowfishCMS 9.0.0' in listing and re.search(r'broken\t1\.0\.0\tinstalled\ttheme\.css: .*import',listing),'blowfishctl’s list of theme folders, with what’s wrong with each')

 # ---- The Themes tab --------------------------------------------------------
 status,html,hdr=run('/admin/?kind=themes',user='admin');csrf=cookie_of(hdr,'bf_csrf');admin='bf_csrf='+csrf
 check(status==200 and '<a href="/admin/?kind=themes" aria-current="page">Themes</a>' in html and '</span>variants</div>' in html and '</span>installed themes</div>' in html and '</span>more themes</div>' in html,'Themes is a tab of Look: variants, installed themes, more themes')
 check('Can’t be used: theme.css' in html and 'needs BlowfishCMS 9.0.0' in html and 'comes with BlowfishCMS' in html,'installed themes say what’s wrong with them')
 side=re.search(r'<nav class="admin-nav"[^>]*>(.*?)</nav>',html,re.S).group(1)
 check('<a href="/admin/?kind=themes" aria-current="page"' in side and '>Look<' in side and re.findall(r'href="([^"]+)"',re.search(r'<nav class="admin-tabs" aria-label="Look">.*?</nav>',html,re.S).group(0))==['/admin/?kind=themes','/admin/?kind=branding'],'Themes is under Look in the sidebar, beside Logo & icons')
 st,h,_=run('/admin/?kind=themes');check(st in (200,303,401,403) and 'admin-shell' not in h and (st!=200 or 'name="password"' in h),'the Themes tab requires the admin login')
 check(run('/admin/?kind=themes&new=1',user='admin')[0]==303,'new themes come as folders: the old “new theme” address goes to the list')
 base={k:'#123456' for k in ['desktop','bg','window','window-2','ink','muted','line','accent','accent-2']}
 base.update({'shadow':'rgba(0,0,0,.4)','font-display':'Georgia,serif','font-ui':'system-ui,sans-serif','font-body':'"Courier New",monospace','maxw':'1100px'})
 def theme(action,**extra):
  f={'csrf':csrf,'kind':'themes','action':action};f.update(extra);return run('/admin/',f,cookie=admin,user='admin')
 def save(**extra):
  f={'name':'Test','scheme':'dark','surfaces':'1'};f.update({'var_'+k:v for k,v in base.items()});f.update(extra);return theme('theme_save',**f)
 html=save(slug='sample',var_bg='red}body{x')[1]
 check('enter a colour' in html and 'admin-notice--error" role="alert"' in html,'unsafe colour rejected, shown as an error')
 editor=run('/admin/?kind=themes&theme=sample',user='admin')[1]
 check('name="css"' not in editor and 'files of <strong>Sample</strong> 1.0.0' in editor and 'name="var_accent"' in editor,'the editor has colours, fonts and width, and no CSS box')
 # Live preview of unsaved colours, drawn with the theme's own CSS.
 f={'name':'Preview','scheme':'dark','surfaces':'1','package':'sample','css':'.evil{color:red}','preview_page':'contact'};f.update({'var_'+k:v for k,v in base.items()});f['var_accent']='#ff00aa'
 status,body,_=run('/admin/',{'csrf':csrf,'kind':'themes','action':'theme_preview','slug':'sample',**f},cookie=admin,user='admin',fetch=True)
 html=json.loads(body)['html'];css_url=re.search(r'href="(/admin/\?kind=themes&amp;preview_css=[a-f0-9]{32})"',html)
 check(status==200 and css_url and 'data-theme="sample"' in html and 'href="/themes.css' not in html and 'contact-form' in html,'theme preview draws the chosen page with only the unsaved variant')
 status,css,hdr=run(css_url.group(1).replace('&amp;','&'),user='admin')
 check(status==200 and 'text/css' in hdr.get('Content-Type','') and '--accent:#ff00aa' in css and ':root[data-theme="sample"] .window__bar' in css and '.evil' not in css,'preview stylesheet holds the unsaved values and the theme’s own CSS, never CSS from the form')
 check(json.loads(run('/admin/',{'csrf':csrf,'kind':'themes','action':'theme_preview','slug':'sample',**{**f,'var_ink':'x;}'}},cookie=admin,user='admin',fetch=True)[1])['ok'] is False,'preview checks values like saving does')
 check(con.execute("select vars from themes where slug='sample'").fetchone()[0].find('#ff00aa')<0,'previewing a theme saves nothing')
 check(run('/admin/?kind=themes&preview_css='+'0'*32,user='admin')[0]==404,'expired preview stylesheets are gone')
 status,_,hdr=save(slug='sample',name='Sample <b>',css='.evil{color:red}')
 check(status==303 and con.execute("select name,css from themes where slug='sample'").fetchone()[:]==('Sample <b>','') and '.evil' not in run('/themes.css')[1],'a variant saves its name and colours; CSS sent with it is ignored')
 check('value="sample"' not in run('/')[1] and '"sample":{"enabled":false' in run('/')[1].replace('&quot;','"'),'a hidden variant isn’t offered to visitors but can be previewed')
 check('can&#39;t be disabled' in theme('theme_disable',slug='modern')[1],'the default variant (Modern) cannot be hidden')
 check('Enable the theme' in theme('theme_default',slug='sample')[1],'a hidden variant cannot become the default')
 theme('theme_enable',slug='sample');theme('theme_default',slug='sample')
 html=run('/')[1];check('data-theme="sample"' in html and '<option value="sample" data-variants="sample" selected>Sample &lt;b&gt;</option>' in html,'a shown default variant is offered, escaped, by its name alone')
 meta=json.loads(H.unescape(re.search(r'<meta name="site-themes" content="([^"]*)"',html).group(1)))
 check('pair' not in meta['themes']['sample'] and 'id="theme-mode"' in html,'a theme with one variant has no light/dark twin (theme.js keeps the switch hidden)')
 before=[r[0] for r in con.execute('select slug from themes order by sort_order')];i=before.index('sample')
 theme('move',id='sample',direction='up')
 check([r[0] for r in con.execute('select slug from themes order by sort_order')]==before[:i-1]+['sample',before[i-1]]+before[i+1:],'variants reorder')
 moved=[r[0] for r in con.execute('select slug from themes order by sort_order')]
 status,body,_=run('/admin/',{'csrf':csrf,'kind':'themes','action':'order','order':['sample','nowhere']},cookie=admin,user='admin',fetch=True)
 check(status==200 and '"ok":true' in body and [r[0] for r in con.execute('select slug from themes order by sort_order')]==['sample']+[s for s in moved if s!='sample'],'variants are dragged into order the way pages are; unknown ones are ignored')
 run('/admin/',{'csrf':csrf,'kind':'themes','action':'order','order':moved},cookie=admin,user='admin',fetch=True)
 adm=run('/admin/?kind=themes',cookie=admin,user='admin')[1]
 check('data-reorder="themes"' in adm and adm.count('data-reorder-id=')==len(moved) and adm.count('class="move-form"')==len(moved),'the Themes list has drag handles, and move up and move down in each row’s menu')
 theme('theme_duplicate',slug='sample')
 check(tuple(con.execute("select enabled,name,package from themes where slug='sample-copy'").fetchone())==(0,'Copy of Sample <b>','sample') and ':root[data-theme="sample-copy"] .window__bar' in run('/themes.css?with=sample-copy')[1],'a duplicate is a hidden variant drawn with the same theme files')
 # Back to the theme's own values (after a change here, or an update that brought new ones).
 editor=run('/admin/?kind=themes&theme=sample',user='admin')[1]
 check('name="action" value="theme_reset"' in editor and 'use the theme’s colours' in editor,'a variant whose values aren’t its theme’s offers the theme’s back')
 status,_,_=theme('theme_reset',slug='sample')
 own=json.loads((pathlib.Path(__file__).resolve().parent/'fixtures/themes/sample/theme.json').read_text())['variants'][0]
 row=con.execute("select name,scheme,surfaces,vars from themes where slug='sample'").fetchone()
 check(status==303 and row[:3]==('Sample','dark',1) and json.loads(row[3])==own['vars'],'“use the theme’s colours” puts back its name, scheme, colours, fonts and width')
 check('value="theme_reset"' not in run('/admin/?kind=themes&theme=sample',user='admin')[1],'once they match, the editor doesn’t offer it')
 check('no values of its theme’s' in theme('theme_reset',slug='sample-copy')[1] and con.execute("select name from themes where slug='sample-copy'").fetchone()[0]=='Copy of Sample <b>','a duplicate has none of its theme’s to go back to, and is left alone')
 check("can&#39;t be deleted" in theme('theme_delete',slug='sample')[1],'the default variant cannot be deleted')
 check('One of its variants is the default' in theme('theme_remove',name='sample')[1] or 'run: doas blowfishctl theme remove sample' in theme('theme_remove',name='sample')[1],'a theme whose variant is the default stays')
 check('doas blowfishctl theme install' in theme('theme_install',name='sample')[1],'without the request runner, installing is left to the server')
 more=run('/admin/?kind=themes',user='admin')[1]
 check('doas blowfishctl theme add FILE.tar.gz' in more and 'github.com' not in more,'without the runner, themes are added on the server; nothing points at GitHub')
 forget=lambda n:subprocess.run(['perl',script,'--theme-forget',n],env=env,capture_output=True,text=True)
 check(forget('sample').returncode==1,'blowfishctl theme remove refuses a theme with the default variant')
 theme('theme_default',slug='modern');theme('theme_delete',slug='sample-copy')
 check(con.execute("select count(*) from themes where slug='sample-copy'").fetchone()[0]==0,'a variant is deleted; its theme stays')
 check(forget('sample').stdout.strip()=='sample: 1 variant deleted' and con.execute("select count(*) from themes where package='sample'").fetchone()[0]==0,'removing a theme deletes its variants')
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
 check([r[0] for r in con.execute("select slug from themes where package='sample' order by sort_order")]==['sample','sample-light'],'installing a removed theme again brings its variants back, hidden')

 # ---- Pages tab, navigation and Links ------------------------------------
 def nav(html):
  m=re.search(r'<div class="site-nav__menu" id="main-menu">(.*?)</div>',html,re.S);return re.findall(r'<a href="([^"]+)"',m.group(1))
 default=['/','/projects/','/photography/','/music/','/blog/','/links/','/resume/','/contact/']
 for page in ['/','/projects/','/resume/','/contact/','/blog/','/photography/']:check(nav(run(page)[1])==default,'navigation unchanged by default on '+page)
 check('aria-current="page">contact' in run('/contact/')[1] and 'aria-current="page">home' in run('/')[1],'current page marked in navigation')
 status,html,hdr=run('/admin/',user='admin');csrf=cookie_of(hdr,'bf_csrf');admin='bf_csrf='+csrf
 check(status==200 and '<h1>Overview</h1>' in html and 'class="admin-cards"' in html and 'class="site-nav' not in html and 'data-theme=' not in html,'admin opens on the overview, without the public navigation or theme')
 check(re.findall(r'<a class="admin-card" href="([^"]+)"',html)==['/admin/?kind=pages','/admin/?kind=photography','/admin/?kind=music','/admin/?kind=video','/admin/?kind=file','/admin/?kind=blog'],'overview counts every library')
 html=run('/admin/?kind=pages',user='admin')[1]
 check('<h1>Pages</h1>' in html and html.count('<article class="theme-row')==8,'pages list opens from the sidebar')
 rows=re.findall(r'<h2>([^<]+?)(?: <span class="state-badge">Off</span>)?</h2>',html);check(rows==['Home','Projects','Photography','Music','Blog','Links','Resume','Contact'],'pages listed in navigation order')
 side=re.search(r'<nav class="admin-nav"[^>]*>(.*?)</nav>',html,re.S).group(1)
 check(re.findall(r'href="([^"]+)"',side)==['/admin/','/admin/','/admin/?kind=pages','/admin/?kind=photography','/admin/?kind=music','/admin/?kind=video','/admin/?kind=file','/admin/?kind=blog','/admin/comments/','/admin/?kind=themes','/admin/?kind=settings','/admin/analytics/','/admin/?kind=addons','/admin/?kind=notices','/','/admin/?kind=account'],'sidebar lists overview, pages, every library, the site tools and your account')
 for screen,path in [('settings','/admin/?kind=settings'),('search','/admin/?kind=search'),('users','/admin/?kind=users'),('signin','/admin/?kind=signin')]:
  page=run(path,cookie=admin,user='admin')[1];tabs=re.search(r'<nav class="admin-tabs".*?</nav>',page,re.S)
  check(tabs and re.findall(r'href="([^"]+)"',tabs.group(0))==['/admin/?kind=settings','/admin/?kind=search','/admin/mail/','/admin/?kind=users','/admin/?kind=signin','/admin/?kind=system'] and 'aria-current="page">Settings' in page,'Settings, Search & sharing, Mail, Users, Sign-in and System are tabs under one sidebar entry ('+screen+')')
 check('aria-current="page">Pages' in side and '>Articles<' in side and 'Blog' not in side,'sidebar marks the current screen and calls the blog library Articles')
 def page_action(action,page,**extra):
  f={'csrf':csrf,'kind':'pages','action':action,'page':page};f.update(extra);return run('/admin/',f,cookie=admin,user='admin')
 page_action('move','',id='contact',direction='up');page_action('move','',id='blog',direction='up')
 check(nav(run('/')[1])==['/','/projects/','/photography/','/blog/','/music/','/links/','/contact/','/resume/'],'navigation reordered everywhere')
 check(nav(run('/contact/')[1])==nav(run('/blog/')[1])==nav(run('/')[1]),'same navigation on template and generated pages')
 page_action('nav_toggle','links');check(run('/links/')[0]==404,'a page turned off answers “not found”')
 check(re.search(r'<h2>Links <span class="state-badge">Off</span></h2>',run('/admin/?kind=pages',cookie=admin,user='admin')[1]),'pages that are off carry an Off badge')
 rows=lambda:re.findall(r'data-reorder-id="([^"]+)"',run('/admin/?kind=pages',cookie=admin,user='admin')[1])
 before=rows()
 status,body,_=run('/admin/',{'csrf':csrf,'kind':'pages','action':'order','order':['blog','home','nowhere']},cookie=admin,user='admin',fetch=True)
 check(status==200 and '"ok":true' in body and rows()==['blog','home']+[x for x in before if x not in ('blog','home')],'dragging rows saves the new order; unknown pages are ignored and the rest keep their place')
 run('/admin/',{'csrf':csrf,'kind':'pages','action':'order','order':before},cookie=admin,user='admin',fetch=True)
 check(rows()==before,'the order can be put back')
 page_action('nav_toggle','links');check('/links/' in nav(run('/')[1]) and run('/links/')[0]==200,'links page turned on')
 for page in ['/','/projects/','/photography/','/music/','/blog/','/links/','/resume/','/contact/']:
  bars=re.findall(r'<div class="window__title">(.{0,80})',run(page)[1])
  check(bars and all(re.match(r'<span class="window__glyph"[^>]*></span>',x) for x in bars),'every window title on '+page+' has its glyph')
 page_action('nav_toggle','music');check('/music/' not in nav(run('/')[1]) and run('/music/')[0]==404,'a page that is off leaves the navigation and answers not found')
 check('/music/' not in run('/sitemap.xml')[1],'a page that is off leaves the sitemap')
 page_action('nav_toggle','music');check(run('/music/')[0]==200,'turned back on')
 check('always on' in page_action('nav_toggle','home')[1],'home cannot be turned off')
 msg={'name':'Pat','email':'pat@example.org','message':'hello'}
 on=run('/contact/send',msg)[0]
 page_action('nav_toggle','contact');check(on!=404 and run('/contact/send',msg)[0]==404,'contact page off: the form stops accepting messages')
 page_action('nav_toggle','contact')
 html=run('/admin/?kind=pages',user='admin')[1];check(re.findall(r'<h2>([^<]+)</h2>',html)[3]=='Blog','pages list follows the new order')
 check('class="admin-crumbs"' in run('/admin/?kind=page&page=photography',user='admin')[1],'page editors show a breadcrumb back to pages')
 check('edit the Photography page' in run('/admin/?kind=photography',user='admin')[1],'a library links to the page that shows it')
 check(run('/admin/?kind=links',user='admin')[0]==303 and 'kind=links' not in run('/admin/',user='admin')[1].split('<main')[0],'Links is no longer a library (it’s the Links add-on since 0.20.1)')

 # ---- Web-size images and gallery protection -------------------------------
 import struct,zlib
 def png(w,h):
  def chunk(k,d):return struct.pack('>I',len(d))+k+d+struct.pack('>I',zlib.crc32(k+d)&0xffffffff)
  base=bytes(v for x in range(w) for v in ((x*3)%256,(x*5)%256,(x*7)%256))
  rows=b''.join(b'\0'+base[y%3:]+base[:y%3] for y in range(h))
  return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(rows))+chunk(b'IEND',b'')
 def dims(path):
  b=pathlib.Path(path).read_bytes()
  if b[:4]==b'RIFF' and b[12:16]==b'VP8X':return (1+int.from_bytes(b[24:27],'little'),1+int.from_bytes(b[27:30],'little'))
  if b[:4]==b'RIFF' and b[12:16]==b'VP8 ':w,h=struct.unpack('<HH',b[26:30]);return (w&0x3fff,h&0x3fff)
  if b[:4]==b'RIFF' and b[12:16]==b'VP8L':v=int.from_bytes(b[21:25],'little');return (1+(v&0x3fff),1+((v>>14)&0x3fff))
  if b[:8]==b'\x89PNG\r\n\x1a\n':return struct.unpack('>II',b[16:24])
  raise ValueError(path)
 def upload(kind,files,**extra):
  boundary='---'+secrets.token_hex(8);parts=[]
  for k,v in {'csrf':csrf,'kind':kind,**extra}.items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
  for key,name,data in files:parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"; filename="{name}"\r\nContent-Type: image/png\r\n\r\n'.encode()+data+b'\r\n')
  body=b''.join(parts)+f'--{boundary}--\r\n'.encode()
  e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST','SCRIPT_NAME':'/admin/','QUERY_STRING':'','CONTENT_TYPE':'multipart/form-data; boundary='+boundary,'CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':admin,'REMOTE_USER':'admin','HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':'192.0.2.1'}
  p=subprocess.run(['perl',script],input=body,env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE);assert p.returncode==0,p.stderr.decode();return p.stdout.decode()
 big=png(3000,2000)
 upload('photography',[('media','wide.png',big)],action='upload',folder='')
 item=con.execute("select * from uploads where title='wide'").fetchone()
 media=root/'media/blowfishcms'
 check(item['filename'].endswith('.webp') and item['mime']=='image/webp' and (item['width'],item['height'])==(2560,1707),'new photos stored as 2560px WebP')
 check(dims(media/'pictures'/item['filename'])==(2560,1707),'stored photo is web-sized')
 check(item['thumbnail'].endswith('-thumb.webp') and max(dims(media/'pictures'/item['thumbnail']))==800,'thumbnail is an 800px WebP')
 html=run('/photography/')[1]
 check('class="photo-open"' in html and 'data-src="/media/pictures/'+item['filename'] in html and 'href="/media/pictures/' not in html and 'target="_blank"' not in html.split('photo-grid')[1],'gallery has no links to open images in a new tab')
 check('viewer-original' not in html and 'open original size' not in html,'viewer has no original-size link')
 check('draggable="false"' in html and re.search(r'/js/site\.js\?v=\d+', html),'gallery images not draggable; the public script loaded')
 upload('blog',[('image','inline.png',big)],action='blog_image',title='Image post',body='Hi')
 body=con.execute("select body from posts where title='Image post'").fetchone()[0]
 name=re.search(r'/media/pictures/articles/([a-f0-9]{32}\.webp)',body).group(1);check(max(dims(media/'pictures/articles'/name))==2560,'article pictures go into the library\'s Articles folder as 2560px WebP')
 check(con.execute("select count(*) from uploads where kind='photography' and folder='articles' and filename=?",(name,)).fetchone()[0]==1,'an article picture is a library picture')
 # A published article with a library picture, for the feed's image links.
 con.execute("insert into posts (id,title,body,published_at,created_at,updated_at) values (?,?,?,?,?,?)",(secrets.token_hex(16),'Picture post','![a](/media/pictures/articles/'+name+')','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z'));con.commit()
 # ---- Blog: share, likes, comments --------------------------------------
 post=con.execute('select id,title from posts where published_at is not null').fetchone()
 if not post:
  pid=secrets.token_hex(16);con.execute("insert into posts (id,title,body,published_at,created_at,updated_at) values (?,?,?,?,?,?)",(pid,'Test post','Hello',"2026-01-01T00:00:00Z","2026-01-01T00:00:00Z","2026-01-01T00:00:00Z"));con.commit()
 else: pid=post['id']
 draft=secrets.token_hex(16);con.execute("insert into posts (id,title,body,published_at,created_at,updated_at) values (?,?,?,NULL,?,?)",(draft,'Draft','x',"2026-01-01T00:00:00Z","2026-01-01T00:00:00Z"));con.commit()
 html=run('/blog/?post='+pid)[1]
 check('data-share' in html and 'data-copy-link' in html and 'https://example.net/blog/?post='+pid in html,'post shows share and copy-link controls')
 check('og:title' in html and 'og:url' in html and '/js/talk.js' in html,'post has share preview tags and script')
 check('action="/talk/like"' not in html and 'comment-form' not in html,'likes and comments hidden until the server is set up')
 (root/'var/db/blowfishcms-comments').mkdir(parents=True)
 html=run('/blog/?post='+pid)[1];check('action="/talk/like"' in html and 'id="comment-form"' in html,'likes and comments appear once set up')
 status,_,hdr=run('/talk/comment',{'item':pid,'name':'Alice É','body':'Hello <b>world</b>\n\nSecond'});alice='bf_visitor='+cookie_of(hdr,'bf_visitor')
 check(status==303 and '&c=ok#comment-' in hdr['Location'] and len(alice)>40,'first comment posts and issues a browser key')
 html=run('/blog/?post='+pid,cookie=alice)[1]
 check('<strong>Alice É</strong>' in html and 'Hello &lt;b&gt;world&lt;/b&gt;</p><p>Second' in html,'comment shown escaped with paragraphs')
 check('value="Alice É"' in html,'returning commenter sees their username')
 check(oct(os.stat(root/'var/db/blowfishcms-comments/comments.sqlite').st_mode&0o777)=='0o644','comments database readable by the gallery worker')
 check(oct(os.stat(root/'var/db/blowfishcms-comments/private/salt.key').st_mode&0o777)=='0o600','comment secret kept private')
 status,_,hdr=run('/talk/comment',{'item':pid,'name':'alice é','body':'imposter'},ip='192.0.2.2')
 check('c=taken' in hdr['Location'],'claimed username protected across browsers (case and accents)')
 check(run('/talk/comment',{'item':pid,'name':'Alice É','body':'again'},cookie=alice)[2]['Location'].count('c=ok')==1,'owner can reuse their username')
 con.execute("insert or replace into site_settings(key,value) values ('author','Robin Example')");con.commit()
 for name in ['Robin','The Admin','admin','x','bad<name>']:
  check(re.search('c=(reserved|name)',run('/talk/comment',{'item':pid,'name':name,'body':'x'},ip='192.0.2.3')[2]['Location']),'username rejected: '+name)
 check('c=links' in run('/talk/comment',{'item':pid,'name':'Linky','body':'http://a http://b www.c'},ip='192.0.2.4')[2]['Location'],'link-heavy comment rejected')
 check('c=dup' in run('/talk/comment',{'item':pid,'name':'Alice É','body':'again'},cookie=alice)[2]['Location'],'duplicate comment rejected')
 run('/talk/comment',{'item':pid,'name':'Alice É','body':'third'},cookie=alice)
 status,body,_=run('/talk/comment',{'item':pid,'name':'Alice É','body':'fourth'},cookie=alice,fetch=True)
 check(status==400 and json.loads(body)['code']=='rate','rapid commenting rate-limited')
 before=sqlite3.connect(root/'var/db/blowfishcms-comments/comments.sqlite').execute('select count(*) from comments').fetchone()[0]
 run('/talk/comment',{'item':pid,'name':'Bot','body':'spam','website':'http://spam'},ip='192.0.2.5')
 check(sqlite3.connect(root/'var/db/blowfishcms-comments/comments.sqlite').execute('select count(*) from comments').fetchone()[0]==before,'spam trap discards bot comments')
 check(run('/talk/comment',{'item':draft,'name':'Bob','body':'x'})[0]==404,'drafts cannot receive comments')
 check(run('/talk/comment',{'item':pid,'name':'Bob','body':'x'},origin='https://evil.example')[0]==403,'foreign sites cannot post comments')
 check(run('/talk/comment')[0]==405,'comment endpoint rejects GET')
 status,body,_=run('/talk/like',{'item':pid},cookie=alice,fetch=True);check(json.loads(body)['liked'] is True and json.loads(body)['count']==1,'like recorded')
 status,body,_=run('/talk/like',{'item':pid},cookie=alice,fetch=True);check(json.loads(body)['liked'] is False and json.loads(body)['count']==0,'second click unlikes')
 run('/talk/like',{'item':pid},cookie=alice);status,body,_=run('/talk/like',{'item':pid},ip='192.0.2.9',fetch=True)
 check(json.loads(body)['count']==2,'likes counted per browser')
 html=run('/blog/?post='+pid,cookie=alice)[1];check('aria-pressed="true"' in html and '2 likes' in html,'post shows like state and count')
 check(re.search(r'♥ 2 · 3 comments',run('/blog/')[1]),'blog list shows likes and comment counts')
 # With the Blog page off, its articles, feed, comments and likes are offline too.
 page_action('nav_toggle','blog')
 check(run('/blog/')[0]==404 and run('/blog/?post='+pid)[0]==404 and run('/blog/feed.xml')[0]==404,'blog off: list, articles and feed not found')
 check(run('/talk/comment',{'item':pid,'name':'Alice É','body':'while off'},cookie=alice)[0]==404 and run('/talk/like',{'item':pid},cookie=alice)[0]==404,'blog off: comments and likes refused')
 check('/blog/?post=' not in run('/sitemap.xml')[1],'blog off: articles leave the sitemap')
 page_action('nav_toggle','blog');check(run('/blog/?post='+pid)[0]==200,'blog back on')

 # ---- Sitemap -------------------------------------------------------------
 import xml.dom.minidom
 status,body,hdr=run('/sitemap.xml');xml.dom.minidom.parseString(body)
 locs=re.findall(r'<loc>https://example\.net([^<]*)</loc>',body)
 check(status==200 and hdr['Content-Type'].startswith('application/xml'),'sitemap served as XML')
 check([l for l in locs if not l.startswith('/blog/?post=')]==nav(run('/')[1]),'sitemap lists exactly the pages in the navigation, in order')
 check('/music/' in locs and '/links/' in locs,'pages that are on are in the sitemap')
 published=[r[0] for r in con.execute('select id from posts where published_at is not null')]
 check(sorted(l.split('=')[1] for l in locs if l.startswith('/blog/?post='))==sorted(published) and draft not in body,'sitemap lists published posts only')
 check(re.search(r'<loc>https://example\.net/blog/\?post='+pid+r'</loc><lastmod>\d{4}-\d\d-\d\d</lastmod>',body),'posts carry a last-modified date')

 # ---- RSS feed -----------------------------------------------------------
 status,body,hdr=run('/blog/feed.xml');doc=xml.dom.minidom.parseString(body)
 check(status==200 and hdr['Content-Type'].startswith('application/rss+xml') and doc.documentElement.getAttribute('version')=='2.0','RSS 2.0 feed served')
 links=[n.firstChild.data for n in doc.getElementsByTagName('item') for n in n.getElementsByTagName('link')]
 newest=[r[0] for r in con.execute('select id from posts where published_at is not null order by published_at desc limit 20')]
 check(links==['https://example.net/blog/?post='+i for i in newest],'feed lists published posts, newest first')
 check(draft not in body,'drafts left out of the feed')
 check(all(re.fullmatch(r'[A-Z][a-z]{2}, \d\d [A-Z][a-z]{2} \d{4} \d\d:\d\d:\d\d \+0000',n.firstChild.data) for n in doc.getElementsByTagName('pubDate')),'feed dates in RSS format')
 check('https://example.net/media/pictures/' in body and 'src="/media' not in body,'feed image links are absolute')
 check(all('href="/blog/feed.xml"' in run(p)[1] and 'application/rss+xml' in run(p)[1] for p in ['/','/blog/','/contact/','/photography/']),'pages announce the feed to readers')
 check('<a href="/blog/feed.xml">RSS feed</a>' in run('/blog/')[1],'blog page links to the feed')

 # ---- Moderation --------------------------------------------------------
 check(run('/admin/comments/')[0] in (303,401,403),'moderation requires the admin login')
 status,html,hdr=run('/admin/comments/',user='admin');mod='bf_comments_csrf='+cookie_of(hdr,'bf_comments_csrf')
 check(status==200 and html.count('<article class="admin-comment')==3,'moderation lists comments')
 cid=re.search(r'name="id" value="([0-9a-f]{32})"',html).group(1)
 check(run('/admin/comments/',{'csrf':'bad','action':'hide','id':cid},cookie=mod,user='admin')[0]==403,'moderation CSRF protected')
 def moderate(action):return run('/admin/comments/',{'csrf':mod.split('=',1)[1],'action':action,'id':cid},cookie=mod,user='admin')
 moderate('hide');check('comment-'+cid not in run('/blog/?post='+pid)[1],'hidden comment removed from the post')
 moderate('show');check('comment-'+cid in run('/blog/?post='+pid)[1],'comment can be shown again')
 moderate('release');check('c=ok' in run('/talk/comment',{'item':pid,'name':'Alice É','body':'mine now'},ip='192.0.2.6')[2]['Location'],'released username can be claimed')
 moderate('delete');check('comment-'+cid not in run('/blog/?post='+pid)[1],'comment deleted')
 check(con.execute("select count(*) from uploads where collection<>'LEGACY' and not (kind='photography' and (title='wide' or folder='articles'))").fetchone()[0]==copied_uploads,'existing uploads preserved in the test copy')
print(json.dumps({'checks':len(checks)}))