repository

BlowfishCMS

A small content management system for OpenBSD

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

181 lines · 16.7 KB · download this file

#!/usr/bin/env python3
"""A second install: another domain, admin account and folders, set by
etc/blowfishcms.conf. Checks that nothing of the built-in defaults or the
sample site leaks into it and
that site settings replace the old hard-coded values. Uses a new site's
catalogue; never touches live data."""
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
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-instance-test-') as tmp:
 root=pathlib.Path(tmp)
 conf=root/'etc/blowfishcms.conf';conf.parent.mkdir(parents=True)
 conf.write_text('# written by the installer\n'
  'domain = example.org\naliases = www.example.org\nadmin_user = alice\n'
  'data = /var/db/bf-example\nmedia = /media/example.org\ncomments = /var/db/bf-example-comments\n'
  'contact = /var/db/bf-example-contact\nsecrets = /etc/example.org\nmail = postmark\nmail_from = site@example.org\n')
 data=root/'var/db/bf-example';(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/example.org'/kind).mkdir(parents=True)
 copied_uploads=start_catalog(data/'catalog.sqlite')
 with signin.connect(data/'catalog.sqlite') as copy:copy.execute("delete from site_settings where key not in ('default_theme','themes_offered')")
 env={**os.environ,'BLOWFISH_ROOT':str(root)}
 pass
 def run(path,fields=None,user='',origin='https://example.org',cookie='',fetch=False,files=None):
  url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {},doseq=True).encode() if fields is not None else b''
  ctype='application/x-www-form-urlencoded'
  if files:
   # multipart/form-data: the fields, then each file as (name, filename, bytes).
   boundary='bftest'+secrets.token_hex(8);parts=[]
   for k,v in (fields or {}).items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
   for name,filename,data in files:parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+data+b'\r\n')
   body=b''.join(parts)+f'--{boundary}--\r\n'.encode();ctype='multipart/form-data; boundary='+boundary
  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':ctype,'CONTENT_LENGTH':str(len(body)),'REMOTE_USER':user,'HTTP_ORIGIN':origin,'HTTP_COOKIE':cookie,'REMOTE_ADDR':'192.0.2.9',**({'HTTP_X_REQUESTED_WITH':'fetch'} if fetch else {})}
  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
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
 check((data/'catalog.sqlite').exists() and not (root/'var/db/blowfishcms').exists(),'the install uses its own folders')

 # ---- Public pages: this domain, neutral defaults --------------------------
 status,html,_=run('/')
 check(status==200 and '<link rel="canonical" href="https://example.org/">' in html,'canonical address uses the install\'s domain')
 check('<p class="site-nav__brand"><a href="/">My site</a></p>' in html,'site title defaults to "My site"')
 # Page titles and descriptions are the copied content; everything else is the install's.
 chrome=re.sub(r'<main.*</main>|<title>.*?</title>|<meta name="description"[^>]*>|<meta property="og:[^>]*>','',html,flags=re.S)
 leaks=[w for w in ['R. Example','Robin Example','example.net'] if w in chrome]
 check(not leaks,'no default or sample-site names outside the page content: '+', '.join(leaks))
 # The site's own pages: whichever are on (a site may have turned off or deleted any but Home).
 others=[a for a in re.findall(r'<a href="(/[a-z0-9-]+/)"',re.search(r'id="main-menu">(.*?)</div>',html,re.S).group(1)) if a!='/']
 check(all(run(a)[0]==200 for a in others),'other pages render: '+(', '.join(others) or 'none on'))
 status,feed,_=run('/blog/feed.xml')
 if run('/blog/')[0]==200:
  check(status==200 and '<link>https://example.org/blog/</link>' in feed and 'example.net' not in feed and 'My site — blog' in feed,'feed uses the domain and the site title')
 else:
  check(status==404,'no Blog page on: no feed')
 check('https://example.org/' in run('/sitemap.xml')[1],'sitemap uses the domain')

 # ---- Admin: the configured account only ----------------------------------
 st,h,_=run('/admin/',user='admin');check(st in (200,303,401,403) and 'admin-shell' not in h and (st!=200 or 'name="password"' in h),'the default admin account has no access here: it gets the login page')
 status,html,hdr=run('/admin/',user='alice')
 check(status==200 and 'My site <span>admin</span>' in html and 'bf_csrf=' in hdr.get('Set-Cookie',''),'the configured admin account gets the admin')
 csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1)
 links=lambda origin:run('/admin/',{'csrf':csrf,'kind':'pages','action':'page_create','label':'Origin '+str(len(origin))+origin[8:11],'slug':''},user='alice',origin=origin,cookie='bf_csrf='+csrf)
 check('Foreign origin' in links('https://example.net')[1],'forms from the default domain are refused')
 check(links('https://www.example.org')[0]==303,'forms from the configured domain and its aliases work')

 # ---- Settings replace the old hard-coded values ---------------------------
 with signin.connect(data/'catalog.sqlite') as c:
  c.executemany('insert into site_settings(key,value) values (?,?) on conflict(key) do update set value=excluded.value',
   [('site_title','Example & Co'),('author','Alice Smith')])
 html=run('/')[1]
 check('<p class="site-nav__brand"><a href="/">Example &amp; Co</a></p>' in html,'site title from the settings, escaped')
 contact=run('/contact/')[1]
 check('data-address' not in contact and 'contact-status' in contact,'the contact form doesn\'t put the receiving address in the page')

 # ---- The settings screen ----------------------------------------------------
 adm=lambda fields,**o:run('/admin/',{'csrf':csrf,'kind':'settings',**fields},user='alice',cookie='bf_csrf='+csrf,**o)
 status,html,_=run('/admin/?kind=settings',user='alice',cookie='bf_csrf='+csrf)
 check(status==200 and 'href="/admin/?kind=settings" aria-current="page"' in html and 'value="Example &amp; Co"' in html,'settings screen opens from the sidebar with the current values')
 base={'action':'settings_save','site_title':'Harbour Notes','footer_text':'© Harbour · [about](/about/) <script>x</script>','author':'Alice Smith','description':'A test site.'}
 status,body,_=adm(base,fetch=True)
 check(status==200 and json.loads(body)['ok'],'settings save in the background')
 html=run('/')[1]
 footer=re.search(r'<footer class="site-footer">(.*?)</footer>',html,re.S)
 check('<a href="/">Harbour Notes</a>' in html and footer and '<a href="/about/">about</a>' in footer.group(1) and '<script>' not in footer.group(1),'site name and footer come from the settings; footer HTML is escaped')
 check('<footer' not in run('/admin/',user='alice',cookie='bf_csrf='+csrf)[1],'no footer in the admin')
 check(not re.search(r'<footer',(adm({**base,'footer_text':''},fetch=True),run('/')[1])[1]),'an empty footer leaves the footer out')
 for bad,why in [({'site_title':''},'empty name'),({'site_title':'a\nb'},'line break in name')]:
  status,body,_=adm({**base,**bad},fetch=True)
  check(status==400 and not json.loads(body)['ok'],'settings refused: '+why)
 check('<a href="/">Harbour Notes</a>' in run('/')[1],'a refused save changes nothing')
 # Favicon: cropped to a square, saved in three sizes, linked from every page.
 png=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->new(300,200,1);$i->filledRectangle(0,0,299,199,$i->colorAllocate(200,30,30));binmode STDOUT;print $i->png'],capture_output=True,check=True).stdout
 status,_,hdr=adm({'action':'favicon_upload'},files=[('favicon','icon.png',png)])
 with signin.connect(data/'catalog.sqlite') as c:fav=c.execute("select value from site_settings where key='favicon'").fetchone()[0]
 site=root/'media/example.org/site'
 made=sorted(p.name for p in site.iterdir())
 check(status==303 and made==sorted(f'icon-{fav}-{n}.png' for n in (32,180,512)),'favicon saved in three sizes')
 dims=subprocess.run(['perl','-MGD','-e','print join ",",map {join "x",GD::Image->new($_)->getBounds} @ARGV',*[str(site/f'icon-{fav}-{n}.png') for n in (32,180,512)]],capture_output=True,text=True).stdout
 check(dims=='32x32,180x180,512x512','favicon images are square: '+dims)
 html=run('/')[1]
 check(f'<link rel="icon" href="/media/site/icon-{fav}-32.png" type="image/png" sizes="32x32">' in html and f'href="/media/site/icon-{fav}-180.png"' in html and 'icon.svg' not in html,'pages link the uploaded favicon')
 check(adm({'action':'favicon_upload'},files=[('favicon','x.png',b'not an image')])[0]==200 and sorted(p.name for p in site.iterdir())==made,'a file that isn\'t a picture is refused and the favicon is kept')
 adm({'action':'favicon_upload'},files=[('favicon','icon.png',png)])
 with signin.connect(data/'catalog.sqlite') as c:fav2=c.execute("select value from site_settings where key='favicon'").fetchone()[0]
 check(fav2!=fav and sorted(p.name for p in site.iterdir())==sorted(f'icon-{fav2}-{n}.png' for n in (32,180,512)),'a new favicon replaces the old files')
 adm({'action':'favicon_reset'})
 check(not list(site.iterdir()) and '/assets/shared/icon.svg' in run('/')[1],'favicon reset goes back to the built-in icon')
 # Logo: beside the name, or instead of it; transparency kept; wide logos fit 640 × 192.
 logo=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->new(1200,300,1);$i->saveAlpha(1);$i->alphaBlending(0);$i->filledRectangle(0,0,1199,299,$i->colorAllocateAlpha(0,0,0,127));$i->filledRectangle(100,50,1100,250,$i->colorAllocate(20,90,160));binmode STDOUT;print $i->png'],capture_output=True,check=True).stdout
 check('<p class="site-nav__brand"><a href="/">Harbour Notes</a></p>' in run('/')[1],'without a logo the header is the site name')
 status,_,_=adm({'action':'logo_upload'},files=[('logo','logo.png',logo)])
 with signin.connect(data/'catalog.sqlite') as c:lid=c.execute("select value from site_settings where key='logo'").fetchone()[0]
 lf=site/f'logo-{lid}.png'
 info=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->newFromPng($ARGV[0],1);my ($w,$h)=$i->getBounds;my $c=$i->getPixel(0,0);print "$w x $h alpha ",($i->alpha($c))',str(lf)],capture_output=True,text=True).stdout
 check(status==303 and info.startswith('640 x 160') and info.endswith('alpha 127'),'logo saved as a PNG that fits 640 × 192, transparency kept: '+info)
 html=run('/')[1]
 check(f'<p class="site-nav__brand site-nav__brand--logo site-nav__brand--medium"><a href="/"><img class="site-nav__logo" src="/media/site/logo-{lid}.png" alt=""><span>Harbour Notes</span></a></p>' in html,'the logo sits beside the site name')
 adm({'action':'logo_options','logo_size':'large','show_site_name':'0'})
 html=run('/')[1]
 check(f'site-nav__brand--large"><a href="/" aria-label="Harbour Notes"><img class="site-nav__logo" src="/media/site/logo-{lid}.png" alt="Harbour Notes"></a>' in html and 'og:site_name" content="Harbour Notes"' in html,'the logo can stand alone, named for screen readers; the site keeps its name elsewhere')
 check(adm({'action':'logo_options','logo_size':'huge','show_site_name':'1'})[0]==200,'an unknown logo size is refused')
 status,_,_=adm({'action':'logo_upload'},files=[('logo','logo.png',logo)])
 with signin.connect(data/'catalog.sqlite') as c:lid2=c.execute("select value from site_settings where key='logo'").fetchone()[0]
 check(lid2!=lid and not lf.exists() and (site/f'logo-{lid2}.png').exists(),'a new logo replaces the old file')
 adm({'action':'logo_remove'})
 check(not (site/f'logo-{lid2}.png').exists() and '<p class="site-nav__brand"><a href="/">Harbour Notes</a></p>' in run('/')[1],'removing the logo goes back to the name')
 # Comment names: the admin account and the author are reserved.
 out=subprocess.run(['perl','-I'+str(pathlib.Path(script).parent.parent/'lib'),'-MBlowfishCMS','-e',
  'BlowfishCMS::handle_request() if 0; $BlowfishCMS::db=BlowfishCMS::database(); print join(",",sort(BlowfishCMS::reserved_words()))'],env=env,capture_output=True,text=True)
 words=out.stdout.split(',')
 check({'alice','smith','harbour','notes'} <= set(words) and 'robin' not in words,'reserved comment names come from this install: '+out.stdout+out.stderr[:200])

 # ---- A broken instance file stops the site rather than guessing -----------
 # (Run directly: a FastCGI worker reads the file when it starts, not per request.)
 script=str(pathlib.Path(__file__).resolve().parent.parent/'cgi-bin/site.pl')
 conf.write_text('domain = example.org/evil\n')
 p=subprocess.run(['perl',script],env={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_NAME':'/','QUERY_STRING':''},capture_output=True,text=True)
 check(p.returncode!=0 and 'domain must be a host name' in p.stderr,'an invalid domain is refused')
 conf.write_text('domain = example.org\ndata = /var/db/../../etc\n')
 p=subprocess.run(['perl',script],env={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_NAME':'/','QUERY_STRING':''},capture_output=True,text=True)
 check(p.returncode!=0 and 'data must be a folder' in p.stderr,'folders can\'t climb out of the chroot')
 conf.write_text('domain = example.org\ncolour = blue\n')
 p=subprocess.run(['perl',script],env={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_NAME':'/','QUERY_STRING':''},capture_output=True,text=True)
 check(p.returncode!=0 and 'unknown setting colour' in p.stderr,'unknown settings are refused')

# ---- A brand-new install: empty catalogue, starter pages -------------------------
with tempfile.TemporaryDirectory(prefix='blowfish-fresh-test-') as tmp:
 root=pathlib.Path(tmp);(root/'etc').mkdir()
 (root/'etc/blowfishcms.conf').write_text('domain = new.example\nadmin_user = bob\ndata = /var/db/bf\nmedia = /media/new.example\ncomments = /var/db/bf-comments\ncontact = /var/db/bf-contact\nsecrets = /etc/new.example\nmail_from = site@new.example\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/new.example'/kind).mkdir(parents=True)
 env={k:v for k,v in os.environ.items() if k != 'BLOWFISH_PAGES_SEED'};env['BLOWFISH_ROOT']=str(root)
 site=str(pathlib.Path(__file__).resolve().parent.parent/'cgi-bin/site.pl')
 out=subprocess.run(['perl',site,'--migrate'],env=env,capture_output=True,text=True)
 check(out.returncode==0 and 'home, contact' in out.stdout,'a fresh install builds its catalogue and the starter pages: '+out.stdout.strip()[-120:]+out.stderr[-300:])
 def get(path):
  path,_,query=path.partition('?')
  p=subprocess.run(['perl',site],env=signin.sign({**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_NAME':path,'QUERY_STRING':query,'REMOTE_USER':'bob'}),capture_output=True)
  head,html=p.stdout.decode().split('\r\n\r\n',1);return int(re.search(r'Status: (\d+)',head).group(1)),html
 status,html=get('/')
 check(status==200 and '<h1 class="block-heading">Welcome</h1>' in html and 'This is your new site' in html,'the homepage welcomes the new owner')
 check('data-theme="modern"' in html,'new installs start with the Modern theme')
 check('about-card' not in html and 'data-theme-profile' not in html and 'block-heading">Welcome' in html,'the starter homepage is ordinary blocks, with no portrait')
 tid=re.search(r'href="/admin/\?kind=themes&amp;theme=([a-z0-9-]+)"',get('/admin/?kind=themes')[1])
 check(tid and 'class="profile-grid' not in get('/admin/?kind=themes&theme='+tid.group(1))[1],'the theme editor has no portrait settings while no page uses the portrait block')
 everything=''.join(get(p)[1] for p in ['/','/contact/','/admin/','/admin/?kind=pages'])
 found=[w for w in ['Robin','example-user','example.net','Lighthouse'] if w.lower() in everything.lower()]
 check(not found,'nothing of the sample site or the defaults anywhere on a new install: '+', '.join(found))
 check(re.findall(r'<a href="(/[^"]*)"[^>]*>(?:home|contact)</a>',re.search(r'id="main-menu">(.*?)</div>',everything,re.S).group(1))==['/','/contact/'],'navigation shows the starter pages, Home and Contact')
 check(get('/projects/')[0]==404,'pages the starter doesn\'t have don\'t exist')
print(json.dumps({'checks':len(checks)}))