repository

BlowfishCMS

A small content management system for OpenBSD

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

136 lines · 9.0 KB · download this file

#!/usr/bin/env python3
"""The update check for a site's own data: migrates a copy of the site's
catalogue (BLOWFISH_TEST_CATALOG; a new site's catalogue when that isn't set)
with this release's code, twice, and checks that nothing the site had is lost
and that everything the site has still works.

It makes no assumption about how the site is laid out: which pages exist or
are on, what blocks they hold, which libraries have anything in them, which
add-ons or theme it uses. It learns all of that from the catalogue and the
admin's own screens, then checks each thing it found. Every other suite tests
the code on a catalogue of its own; this is the only one that reads the
site's. Never touches live data, credentials or media."""
import sys,pathlib;sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import fresh_catalog
import os,tempfile,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())
source=os.environ.get('BLOWFISH_TEST_CATALOG') or ''
checks=[]
def check(v,msg):
 assert v,msg
 checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-upgrade-test-') as tmp:
 root=pathlib.Path(tmp)
 conf=root/'etc/blowfishcms.conf';conf.parent.mkdir(parents=True)
 conf.write_text('domain = example.org\nadmin_user = owner\ndata = /var/db/bf\nmedia = /media/bf\ncomments = /var/db/bf-comments\ncontact = /var/db/bf-contact\nsecrets = /etc/bf\n')
 data=root/'var/db/bf';(data/'admin/tmp').mkdir(parents=True)
 (data/'admin/csrf.key').write_text(secrets.token_hex(32))
 for kind in ['photography','music','artwork','blog','video']:(root/'media/bf'/kind).mkdir(parents=True)
 (root/'var/db/bf-contact').mkdir(parents=True);(root/'var/db/bf-comments').mkdir(parents=True)
 db=data/'catalog.sqlite'
 with signin.connect(source if source and os.path.exists(source) else fresh_catalog()) as original,signin.connect(db) as copy:original.backup(copy)
 env={**os.environ,'BLOWFISH_ROOT':str(root)}
 for k in ['BLOWFISH_PAGES_SEED','BLOWFISH_TEST_CATALOG']:env.pop(k,None)  # (BLOWFISH_ADDONS_PATH stays: it's where this site's add-ons are)
 def sql(q,a=()):
  with signin.connect(db) as c:
   try:return c.execute(q,a).fetchall()
   except sqlite3.OperationalError:return []
 # What the site has before the update.
 tables={t for (t,) in sql("select name from sqlite_master where type='table'")}
 before={
  'uploads':{(i,k) for i,k in sql('select id,kind from uploads')},
  'pages':{s for (s,) in sql('select slug from pages')},
  'blocks':{i for (i,) in sql('select id from page_blocks')},
  'posts':{i for (i,) in sql('select id from posts')},
  'settings':{k for (k,) in sql('select key from site_settings')},
  'themes':{s for (s,) in sql('select slug from themes')},
 }
 print('the site has:',json.dumps({k:len(v) for k,v in before.items()}),flush=True)

 # ---- The migration ---------------------------------------------------------------------
 for n in (1,2):
  p=subprocess.run(['perl',script,'--migrate'],env=env,capture_output=True,text=True)
  check(p.returncode==0,f'the catalogue migrates (run {n}){"" if p.returncode==0 else ": "+(p.stderr or p.stdout)[-600:]}')
 subprocess.run(['perl',script,'--comments-init'],env=env,check=True,capture_output=True)
 # The admin is looked at as one of the site's own owners (a site with admin
 # users only lets its owners see the owners' screens); a site without any yet
 # is looked at as its install's admin account.
 owners=[n for (n,) in sql("select name from admin_users where role='owner' order by created_at,name")]
 me=owners[0] if owners else 'owner'
 conf.write_text(conf.read_text().replace('admin_user = owner',f'admin_user = {me}'))
 # On a site that requires two-step sign-in, its owners have it set up, but
 # their keys aren't in this copy (they're never in the catalogue), so the
 # migration marks them as not having it and the admin would send this check
 # to set it up. Mark the owner it signs in as as having it, as on the site.
 sql("update admin_users set mfa=1 where name=?",(me,))
 after={
  'uploads':{(i,k) for i,k in sql('select id,kind from uploads')},
  'pages':{s for (s,) in sql('select slug from pages')},
  'blocks':{i for (i,) in sql('select id from page_blocks')},
  'posts':{i for (i,) in sql('select id from posts')},
  'settings':{k for (k,) in sql('select key from site_settings')},
  'themes':{s for (s,) in sql('select slug from themes')},
 }
 # Every add-on the site has on is installed (in /opt/blowfishcms-addons, where
 # the site's own add-ons live) and suits this release, or the site would lose it.
 listed=subprocess.run(['perl',script,'--addons'],env=env,capture_output=True,text=True).stdout
 status={l.split('\t')[0]:l.split('\t') for l in listed.splitlines() if l.strip()}
 # The add-ons bundled with this release (catalog/addons): one installed that doesn't suit it
 # is updated to its bundled version right after the switch-over, so that one suiting is enough.
 bundled_dir=pathlib.Path(script).resolve().parents[1]/'catalog/addons'
 bundled={}
 if bundled_dir.is_dir():
  out=subprocess.run(['perl',script,'--addons'],env={**env,'BLOWFISH_ADDONS_PATH':str(bundled_dir)},capture_output=True,text=True).stdout
  bundled={l.split('\t')[0]:l.split('\t') for l in out.splitlines() if l.strip()}
 for name in json.loads((sql("select value from site_settings where key='addons'") or [('[]',)])[0][0] or '[]'):
  row=status.get(name)
  if (row is None or row[3]!='ok') and name in bundled and bundled[name][3]=='ok':row=bundled[name]
  check(row is not None and row[3]=='ok',f'the add-on {name} is installed and works with this release'+('' if row else ' (it isn\'t in /opt/blowfishcms-addons: install it there first)') +('' if not row or row[3]=='ok' else f' ({row[3]})'))
 for what in before:
  lost=before[what]-after[what]
  check(not lost,f'every one of the site\'s {what} is still there'+(f' (missing: {sorted(lost)[:5]})' if lost else ''))

 # ---- The site, as visitors see it -----------------------------------------------------------
 def run(path,user=''):
  url=urllib.parse.urlsplit(path)
  e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_NAME':url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,'REMOTE_USER':user,'REMOTE_ADDR':'192.0.2.50'}
  p=subprocess.run(['perl',script],env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  if p.returncode!=0 or b'\r\n\r\n' not in p.stdout:return 599,p.stderr.decode(errors='replace')[-400:]
  head,body=p.stdout.split(b'\r\n\r\n',1);status=int(re.search(rb'Status: (\d+)',head).group(1))
  return status,body.decode(errors='replace')
 # The pages, as the admin lists them: address, and on or off.
 status,listing=run('/admin/?kind=pages',user=me)
 check(status==200,f'the admin lists the pages (status {status})')
 rows=re.findall(r'<article class="theme-row" data-reorder-id="([^"]+)">.*?<p class="media-label">([^<· ]+)(.*?)</p>',listing,re.S)
 check(rows and rows[0][0]=='home','the site has its pages, Home first')
 on=[(slug,H.unescape(path)) for slug,path,rest in rows if 'visitors get “not found”' not in H.unescape(rest)]
 off=[(slug,H.unescape(path)) for slug,path,rest in rows if 'visitors get “not found”' in H.unescape(rest)]
 for slug,path in on:
  s,_=run(path);check(s==200,f'{path} (on) opens for visitors (status {s})')
 for slug,path in off:
  s,_=run(path);check(s==404,f'{path} (off) answers “not found” (status {s})')
 for path in ['/robots.txt','/sitemap.xml','/themes.css']:
  s,_=run(path);check(s==200,f'{path} answers (status {s})')
 blog_on=any(slug=='blog' for slug,_ in on)
 s,_=run('/blog/feed.xml')
 check(s==(200 if blog_on else 404),f'the feed {"answers" if blog_on else "answers “not found” while Blog is off"} (status {s})')
 published=[i for (i,) in sql("select id from posts where status='published'")]
 if blog_on:
  for i in published[:50]:
   s,_=run(f'/blog/?post={i}');check(s==200,f'published article {i} opens (status {s})')
 s,sitemap=run('/sitemap.xml')
 listed=set(re.findall(r'<loc>https://example\.org([^<]*)</loc>',sitemap))
 check(all(H.unescape(p) in listed for _,p in on) and not any(H.unescape(p) in listed for _,p in off),'the sitemap lists exactly the pages that are on')

 # ---- The site, as its owner sees it -----------------------------------------------------------
 screens=['/admin/']+[f'/admin/?kind=page&page={urllib.parse.quote(slug)}' for slug,_,_ in rows]
 # Every screen the Overview links to, and the tabs of Settings and Look.
 screens+=sorted({H.unescape(h) for p in ['/admin/','/admin/?kind=settings','/admin/?kind=themes'] for h in re.findall(r'href="(/admin/\?kind=[a-z_-]+)"',run(p,user=me)[1])})
 for path in screens:
  s,body=run(path,user=me)
  check(s==200,f'the admin screen {path} opens (status {s}{"; "+body[-300:] if s>=500 else ""})')
 for i in sorted(before['posts'])[:50]:
  s,_=run(f'/admin/?kind=blog&edit={i}',user=me);check(s==200,f'article {i} opens in the editor (status {s})')
print(json.dumps({'checks':len(checks),'site':{k:len(v) for k,v in before.items()}}))