BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
224 lines · 21.0 KB · download this file
#!/usr/bin/env python3
"""The System screen: owners file update, rollback and backup requests for
`blowfishctl requests` (root's crontab) to carry out; releases are saved with
a size limit; one request at a time; results and logs are shown; backups
download (streamed) and can be deleted; editors can't open any of it. The
runner itself is rehearsed on fakebsd. Uses a fresh catalogue."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,time,gzip,io
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)
def bcrypt(pw):return subprocess.run(['perl','-e','print crypt($ARGV[0],"\\$2b\\$10\\$".join("",map {("a".."z")[rand 26]} 1..22))',pw],capture_output=True,text=True).stdout
with tempfile.TemporaryDirectory(prefix='blowfish-system-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 = alice\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)
sk=root/'etc/blowfishcms-session';sk.mkdir(parents=True);(sk/'session.key').write_text(secrets.token_hex(32)+'\n')
env={**os.environ,'BLOWFISH_ROOT':str(root)}
for k in ['BLOWFISH_PAGES_SEED','BLOWFISH_ADDONS_PATH']:env.pop(k,None)
subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
subprocess.run(['perl',script,'--set-password','alice'],input=bcrypt('alice password one'),env=env,check=True,capture_output=True,text=True) # the first owner, as blowfishctl install makes it
subprocess.run(['perl',script,'--comments-init'],env=env,check=True,capture_output=True)
sysd=data/'system'
def raw(path,body=b'',ctype='application/x-www-form-urlencoded',cookie='',method=None,length=None):
url=urllib.parse.urlsplit(path)
e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':method or ('POST' if body else 'GET'),'SCRIPT_NAME':url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
'CONTENT_TYPE':ctype,'CONTENT_LENGTH':str(len(body) if length is None else length),'REMOTE_USER':'','HTTP_ORIGIN':'https://example.org','HTTP_COOKIE':cookie,'REMOTE_ADDR':'192.0.2.7'}
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,rest=p.stdout.split(b'\r\n\r\n',1);hdr={}
for line in head.decode().split('\r\n'):k,v=line.split(': ',1);hdr[k]=v
return int(hdr['Status']),rest,hdr
def run(path,fields=None,cookie=''):
s,b,h=raw(path,urllib.parse.urlencode(fields).encode() if fields is not None else b'',cookie=cookie,method='POST' if fields is not None else 'GET')
return s,H.unescape(b.decode()),h
def multipart(path,fields,files,cookie,length=None):
bnd='----bf'+secrets.token_hex(8);out=io.BytesIO()
for k,v in fields.items():out.write(f'--{bnd}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
for k,(fn,content) in files.items():out.write(f'--{bnd}\r\nContent-Disposition: form-data; name="{k}"; filename="{fn}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+content+b'\r\n')
out.write(f'--{bnd}--\r\n'.encode())
s,b,h=raw(path,out.getvalue(),'multipart/form-data; boundary='+bnd,cookie,length=length)
return s,H.unescape(b.decode()),h
def cookie_of(hdr,name):
m=re.match(name+r'=([^;]*)',hdr.get('Set-Cookie',''));return m.group(1) if m else None
csrf=cookie_of(run('/admin/?kind=login')[2],'bf_csrf')
def sign_in(user,password):
status,_,hdr=run('/admin/',{'csrf':csrf,'kind':'login','user':user,'password':password,'next':'/admin/'},cookie='bf_csrf='+csrf)
s=cookie_of(hdr,'bf_session');return f'bf_csrf={csrf}; bf_session={s}' if status==303 and s else None
alice=sign_in('alice','alice password one')
act=lambda ck,f:run('/admin/',{'csrf':csrf,'kind':'system',**f},cookie=ck)
requests=lambda:sorted((sysd/'requests').glob('*.json'))
# ---- Before the server is set up ------------------------------------------------------
status,html,_=run('/admin/?kind=system',cookie=alice)
check(status==200 and 'hasn’t been set up' in html,'the screen says so when the server has no System folders yet')
check(re.search(r'<nav class="admin-tabs".*?href="/admin/\?kind=system" aria-current="page"',html,re.S) and 'aria-current="page">Settings' in html,'System is a tab of Settings')
for d in ['requests','releases','results','downloads']:(sysd/d).mkdir(parents=True)
# ---- The screen -----------------------------------------------------------------------
html=run('/admin/?kind=system',cookie=alice)[1]
check('hasn’t picked up requests yet' in html,'it warns when the runner has never run')
(sysd/'results/state.json').write_text(json.dumps({'release':'20261116T120000Z','kept':['20261101T090000Z'],'checked':int(time.time())}))
html=run('/admin/?kind=system',cookie=alice)[1]
ver=re.search(r"\$VERSION='([0-9.]+)'",(pathlib.Path(script).resolve().parent.parent/'lib/BlowfishCMS.pm').read_text()).group(1)
check('hasn’t picked up' not in html and f'This site runs BlowfishCMS <strong>{ver}</strong>.</p>' in html and 'Live release' not in html and 'Can roll back' not in html and '</span>release</div>' in html and '</span>roll back</div>' not in html and '</span>update</div>' not in html,'it shows the release’s version, without a box of its own')
check(re.search(r'value="system_rollback".*?<button class="buttonlike" type="submit">roll back</button>',html,re.S),'roll back is offered when there’s an earlier release')
check(f'<dt>BlowfishCMS</dt><dd>{ver}</dd>' in run('/admin/',cookie=alice)[1],'the Overview shows the version')
check('name="signature"' not in html and 'release key' not in html.lower() and not re.search(r'value="system_update".*?<button[^>]*disabled',html,re.S),'update needs only the release: no key or signature')
(sysd/'results/state.json').write_text(json.dumps({'release':'20261116T120000Z','kept':['20261101T090000Z'],'checked':int(time.time())-900}))
html=run('/admin/?kind=system',cookie=alice)[1]
check('hasn’t picked up requests for 15 minutes' in html,'it warns when the runner has stopped')
# A long update holds the runner's lock, so its check-ins stop: no warning while its log keeps changing.
rid=secrets.token_hex(16);(sysd/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'running','action':'update','by':'alice','arg':'','at':int(time.time())-600}))
(sysd/f'results/{rid}.log').write_text('running the pages tests\n')
check('hasn’t picked up' not in run('/admin/?kind=system',cookie=alice)[1],'no warning while an update is running and writing its log')
os.utime(sysd/f'results/{rid}.log',(time.time()-1800,time.time()-1800))
check('hasn’t picked up requests for 15 minutes' in run('/admin/?kind=system',cookie=alice)[1],'but a running request whose log has stopped for 15 minutes still warns')
for ext in ['json','log']:(sysd/f'results/{rid}.{ext}').unlink()
(sysd/'results/state.json').write_text(json.dumps({'release':'20261116T120000Z','kept':['20261101T090000Z'],'checked':int(time.time())}))
st=json.loads((sysd/'results/state.json').read_text());(sysd/'results/state.json').write_text(json.dumps({**st,'off':1}))
html=run('/admin/?kind=system',cookie=alice)[1]
check('turned off on this server' in html and 'system_update' not in html,'when the server has turned the screen off, it says so and offers nothing')
(sysd/'results/state.json').write_text(json.dumps(st))
# ---- Where updates come from ------------------------------------------------------------
html=run('/admin/?kind=system',cookie=alice)[1]
check('New releases aren’t looked for' in html and 'value="system_releases_check"' not in html and 'name="address" type="url"' in html,'without an address, new releases aren’t looked for, and the screen asks where they come from')
for bad in ['http://example.org/x/repos/','https://example.org/x/repos/?a=b','javascript:alert(1)','https://exa mple.org/','https://example.org/x/"r"/']:
check(act(alice,{'action':'system_updates_from','address':bad})[0]==200 and not requests(),'an address that isn’t a plain https one is refused: '+bad[:28])
status,_,_=act(alice,{'action':'system_updates_from','address':'https://example.org/x/repos/'})
req=json.loads(requests()[0].read_text())
check(status==303 and req['action']=='updates_from' and req['address']=='https://example.org/x/repos/' and req['arg']=='','a good one files a request, with the address for root to check and keep')
requests()[0].unlink()
act(alice,{'action':'system_updates_from','address':''});req=json.loads(requests()[0].read_text());requests()[0].unlink()
check(req['address']=='none','an empty one asks to stop looking')
(sysd/'results/state.json').write_text(json.dumps({**st,'updates_from':'https://example.org/x/repos/'}))
html=run('/admin/?kind=system',cookie=alice)[1]
check('value="https://example.org/x/repos/" placeholder' in html and 'value="system_releases_check"' in html and 'Not checked for new releases yet' in html,'once it’s set, the screen shows it and offers to check')
(sysd/'results/state.json').write_text(json.dumps(st))
# ---- Updating --------------------------------------------------------------------------
tgz=gzip.compress(b'not really a release, but gzip')
html=run('/admin/?kind=system',cookie=alice)[1]
check('action="/admin/?kind=system&upload=release" enctype="multipart/form-data"' in html,'the update form says it carries a release, so an oversized one is refused unread')
up=lambda rel:multipart('/admin/?kind=system&upload=release',{'csrf':csrf,'kind':'system','action':'system_update'},{'release':('blowfishcms.tar.gz',rel)},alice)
check('.tar.gz archive' in up(b'PK\x03\x04zip')[1] and not requests(),'only gzip archives are taken')
# An upload that says it's larger than a release can be is refused from its
# size alone, without being read (so the test needn't send 64 MB).
big=multipart('/admin/?kind=system&upload=release',{'csrf':csrf,'kind':'system','action':'system_update'},{'release':('blowfishcms.tar.gz',b'\x1f\x8b'+b'0'*1024)},alice,length=65*1048576+1)
check(big[0]==413 and 'smaller than 64 MB' in big[1] and not requests() and not list((sysd/'releases').iterdir()),'releases over 64 MB are refused unread and nothing is left behind')
status,html,hdr=up(tgz)
check(status==303 and len(requests())==1,'an owner uploads a release and files an update request')
req=json.loads(requests()[0].read_text());rid=requests()[0].stem
check(req['action']=='update' and req['by']=='alice' and (sysd/f'releases/{rid}.tar.gz').read_bytes()==tgz,'the release is saved under the request\'s id')
html=run('/admin/?kind=system',cookie=alice)[1]
check('Waiting for the server to start the update' in html and 'Working on a request' not in html and 'data-refresh="5"' in html,'while it waits, the screen says so in the progress box and refreshes itself')
check('still busy' in act(alice,{'action':'system_backup'})[1] and len(requests())==1,'one request at a time')
# The runner takes it: the request goes, a result comes.
requests()[0].unlink()
(sysd/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'running','action':'update','by':'alice','at':int(time.time())}))
(sysd/f'results/{rid}.log').write_text('checking the release\nsha256 of the uploaded release: 0123\n<b>not markup</b>\n')
check('still busy' in act(alice,{'action':'system_rollback'})[1],'a running request also blocks a new one')
html=run(f'/admin/?kind=system&log={rid}',cookie=alice)[1]
check('sha256 of the uploaded release' in html and b'<b>not markup</b>' in raw(f'/admin/?kind=system&log={rid}',cookie=alice)[1],'the log is shown, escaped')
check('data-refresh="5"' in html,'a running request\'s log refreshes itself')
(sysd/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'failed','action':'update','by':'alice','at':int(time.time())}))
html=run('/admin/?kind=system',cookie=alice)[1]
check(re.search(r'<td>update</td><td>alice</td><td class="system-status system-status--failed">failed</td>',html) and 'Working on' not in html,'finished requests are listed with their result')
check(run('/admin/?kind=system&log=../../etc',cookie=alice)[0]==404 and run('/admin/?kind=system&log='+'0'*32,cookie=alice)[0]==404,'logs are found by id only')
# ---- Rolling back and backing up ---------------------------------------------------------
status,_,_=act(alice,{'action':'system_rollback'})
check(status==303 and [json.loads(p.read_text())['action'] for p in requests()]==['rollback'],'an owner asks for a rollback')
for p in requests():p.unlink()
status,_,_=act(alice,{'action':'system_backup'})
check(status==303 and [json.loads(p.read_text())['action'] for p in requests()]==['backup'],'an owner asks for a backup')
for p in requests():p.unlink()
# ---- Downloads ---------------------------------------------------------------------------
name='example-20261116T130000Z.tar.gz';blob=os.urandom(3*1048576+123)
(sysd/'downloads'/name).write_bytes(blob);(sysd/'downloads/notes.txt').write_text('not a backup')
html=run('/admin/?kind=system',cookie=alice)[1]
check(f'download={name}' in html and 'notes.txt' not in html,'backups are offered for download, nothing else in the folder')
status,body,hdr=raw(f'/admin/?kind=system&download={name}',cookie=alice)
check(status==200 and body==blob and hdr['Content-Length']==str(len(blob)) and name in hdr['Content-Disposition'],'a backup downloads whole (streamed after the headers)')
check(raw('/admin/?kind=system&download=notes.txt',cookie=alice)[0]==404 and raw('/admin/?kind=system&download=../../catalog.sqlite',cookie=alice)[0]==404,'only listed backups download')
check(raw(f'/admin/?kind=system&download={name}')[0] in (302,303) or b'name="password"' in raw(f'/admin/?kind=system&download={name}')[1],'downloads need a signed-in owner')
status,_,_=act(alice,{'action':'backup_remove','name':name})
check(status==303 and [(json.loads(p.read_text())['action'],json.loads(p.read_text())['arg']) for p in requests()]==[('backup_remove',name)],'deleting a backup is a request for the server')
for p in requests():p.unlink()
check('no longer available' in act(alice,{'action':'backup_remove','name':'example-20200101T000000Z.tar.gz'})[1] and not requests(),'only listed backups can be deleted')
# ---- Nightly backups -------------------------------------------------------------------
plan=lambda:subprocess.run(['perl',script,'--backup-plan'],env=env,capture_output=True,text=True).stdout.strip()
html=run('/admin/?kind=system',cookie=alice)[1]
check(html.count('back up now</button>')==1 and 'nightly backups</' not in html and re.search(r'>backups</.*?back up now.*?id="nightly"',html,re.S),'backups and nightly backups share one box')
check('hasn’t run yet' in html and re.search(r'name="backup_nightly" value="1" checked',html) and plan()=='on 14','nightly backups are on by default, keeping 14')
check('between 1 and 30' in act(alice,{'action':'backup_plan','backup_nightly':'1','backup_keep':'0'})[1] and 'between 1 and 30' in act(alice,{'action':'backup_plan','backup_nightly':'1','backup_keep':'31'})[1] and plan()=='on 14','how many to keep must be 1 to 30')
status,_,_=act(alice,{'action':'backup_plan','backup_nightly':'1','backup_keep':'5'})
check(status==303 and plan()=='on 5','an owner chooses how many nightly backups to keep (the server reads it with --backup-plan)')
act(alice,{'action':'backup_plan','backup_keep':'5'})
check(plan()=='off 5' and not re.search(r'name="backup_nightly" value="1" checked',run('/admin/?kind=system',cookie=alice)[1]),'and can turn them off')
act(alice,{'action':'backup_plan','backup_nightly':'1','backup_keep':'14'})
st=json.loads((sysd/'results/state.json').read_text())
(sysd/'results/state.json').write_text(json.dumps({**st,'nightly':{'count':3,'bytes':3*52428800,'status':'failed','at':int(time.time())-3*3600,'message':'not enough free disk space for another backup; delete some, or keep fewer'},'free':40*1048576}))
html=run('/admin/?kind=system',cookie=alice)[1]
check('failed 3 hours ago: not enough free disk space' in html and '3 (150.0 MB)' in html and '40.0 MB' in html,'the screen shows how last night went, the space nightly backups take and what\'s free')
(sysd/'results/state.json').write_text(json.dumps(st))
# ---- Editors ---------------------------------------------------------------------------
run('/admin/',{'csrf':csrf,'kind':'users','action':'user_add','name':'bob','email':'','role':'editor','password':'bob password one','password2':'bob password one'},cookie=alice)
bob=sign_in('bob','bob password one')
check(bob and run('/admin/?kind=system',cookie=bob)[0]==403 and raw(f'/admin/?kind=system&download={name}',cookie=bob)[0]==403,'editors can\'t open the System screen or download backups')
check(act(bob,{'action':'system_backup'})[0]==403 and not requests(),'editors can\'t file requests')
nav=re.search(r'<nav class="admin-nav".*?</nav>',run('/admin/',cookie=bob)[1],re.S).group(0)
check('kind=system' not in nav,'editors don\'t see System in the sidebar')
# ---- An update's progress ------------------------------------------------------------
for f in list((sysd/'requests').glob('*.json'))+list((sysd/'results').glob('*.json')):
if f.name!='state.json':f.unlink()
(sysd/'requests'/(secrets.token_hex(16)+'.json')).write_text(json.dumps({'action':'update','by':'alice','at':int(time.time())}))
html=run('/admin/?kind=system',cookie=alice)[1]
check('<progress max="100" value="0"' in html and 'Waiting for the server to start the update' in html and 'data-refresh="5"' in html,'an uploaded update shows a progress bar while it waits')
for f in (sysd/'requests').glob('*.json'):f.unlink()
rid=secrets.token_hex(16);now=int(time.time())
(sysd/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'running','action':'update','by':'alice','arg':'','at':now-120}))
html=run('/admin/?kind=system',cookie=alice)[1]
check(re.search(r'<progress max="100" aria-label',html) and 'Updating… follow it in the log' in html and f'log={rid}' in html,'an update with no steps written yet shows a moving bar and the log')
box=lambda h:re.search(r'<div class="system-progress".*?</div>',h,re.S).group(0)
prog=lambda d:(sysd/f'results/{rid}.progress').write_text(json.dumps(d))
prog({'step':4,'steps':20,'key':'test:pages','label':'Running the pages tests (3 of 13 test suites)','started':now-90,'at':now-10,'done':{'check':5,'test:upgrade':40,'test:integration':35}})
html=run('/admin/?kind=system',cookie=alice)[1]
check('Running the pages tests (3 of 13 test suites)' in html and 'step 4 of 20' in html and 'started 1 minute ago' in html and re.search(r'value="(\d+)"',box(html)),'a running update shows its step, how far it is and when it started')
pct=int(re.search(r'<progress max="100" value="(\d+)"',html).group(1))
check(10<=pct<=30 and 'minute' in box(html),'with no earlier update to go by, it estimates from the steps so far')
(sysd/'results/update-timings.json').write_text(json.dumps({'done':{'check':5,'test:upgrade':40,'test:integration':35,'test:pages':30,'snapshot':5,'migrate':5,'switch':2,'restart':10,'smoke':5,'httpd':3}}))
html=run('/admin/?kind=system',cookie=alice)[1]
pct=int(re.search(r'<progress max="100" value="(\d+)"',html).group(1))
# 90 s gone; left: 20 s of pages + 30 s of the steps to come = 50 s.
check(60<=pct<=68 and 'Less than a minute left' in html,'the last update’s step times give the estimate')
(sysd/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'done','action':'update','by':'alice','arg':'','at':now}))
html=run('/admin/?kind=system',cookie=alice)[1]
check('<progress' not in html and 'data-refresh="0"' in html,'a finished update shows no bar')
# ---- The manual (man blowfishctl) ----------------------------------------------------
app=pathlib.Path(script).resolve().parent.parent
ctl=(app/'bin/blowfishctl').read_text();page=(app/'man/blowfishctl.8').read_text()
main=ctl[ctl.rindex('\ncase $cmd in'):]
commands=sorted(set(re.findall(r'^([a-z][a-z-]*)\)',main,re.M))-{'help'})
missing=[c for c in commands if not re.search(r'^\.(?:It |Nm blowfishctl\n)?\.?Cm '+re.escape(c)+r'\b',page,re.M) and f'.Cm {c}' not in page and f'Cm {c}' not in page]
check(len(commands)>15 and not missing,'every blowfishctl command is in its manual'+(f' (missing: {missing})' if missing else ''))
addon=ctl[ctl.index('cmd_addon() {'):];addon=addon[:addon.index('\n}\n')]
subs=sorted(set(re.findall(r'^\t([a-z|]+)\)',addon,re.M)))
subs=sorted({x for s in subs for x in s.split('|')})
check(subs and all(f'Cm addon {x}' in page or f'.Cm {x}' in page or f'| {x}' in page or f'{x} |' in page for x in subs),'every add-on command is in the manual')
check(page.startswith('.\\"') and '.Dt BLOWFISHCTL 8' in page and '.Sh SYNOPSIS' in page and '.Sh FILES' in page,'the manual is an mdoc page for section 8')
print(f'{len(checks)} checks passed')