BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
147 lines · 12.9 KB · download this file
#!/usr/bin/env python3
"""Notifications: newer releases of BlowfishCMS (from where updates come from, as the server
found them), of the add-ons and of the themes installed show to owners in the
sidebar, once as a pop-up, and on the Notifications screen, where they can be
dismissed; the System screen offers a one-click update; the server emails the
alerts address each notice once, through Postmark. Uses a fresh catalogue."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,time,gzip,io
import html as H
script=str(pathlib.Path(sys.argv[1]).resolve())
checks=[]
def check(v,msg):
assert v,msg
checks.append(msg);print('PASS',msg,flush=True)
import http.server,threading
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent));import signin # signs requests in (REMOTE_USER → session cookie)
sent=[]
class Postmark(http.server.BaseHTTPRequestHandler):
def log_message(self,*a):pass
def do_POST(self):
body=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
ok=self.headers.get('X-Postmark-Server-Token')=='good-token'
if ok:sent.append(body)
data=json.dumps({'ErrorCode':0,'MessageID':'m%d'%len(sent),'Message':'OK'} if ok else {'ErrorCode':10,'Message':'Bad token'}).encode()
self.send_response(200 if ok else 401);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Postmark)
threading.Thread(target=server.serve_forever,daemon=True).start()
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-notices-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),'BLOWFISH_ADDONS_PATH':str(pathlib.Path(__file__).resolve().parent/'fixtures/addons'),'BLOWFISH_THEMES_PATH':str(pathlib.Path(__file__).resolve().parent/'fixtures/themes'),'BLOWFISH_POSTMARK_API':'http://127.0.0.1:%d'%server.server_port}
env.pop('BLOWFISH_PAGES_SEED',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)
for d in ['requests','releases','results','downloads']:(sysd/d).mkdir(parents=True)
(sysd/'results/state.json').write_text(json.dumps({'release':'x','kept':[],'checked':int(time.time())}))
ver=re.search(r"\$VERSION='([0-9.]+)'",(pathlib.Path(script).resolve().parent.parent/'lib/BlowfishCMS.pm').read_text()).group(1)
major,minor,patch=map(int,ver.split('.'));newer=f'{major}.{minor+1}.0'
subprocess.run(['perl',script,'--addon-enable','hello'],env=env,capture_output=True)
def page(path='/admin/'):return run(path,cookie=alice)[1]
def count(html):m=re.search(r'Notifications <span class="admin-nav__count"[^>]*>(\d+)</span>',html);return int(m.group(1)) if m else 0
# ---- Nothing new ----------------------------------------------------------------
html=page()
check('href="/admin/?kind=notices"' in html and count(html)==0 and 'class="toasts"' not in html,'owners have a Notifications link, with nothing to count')
site=html.split('<p class="admin-nav__group">Site</p>')[1].split('<a class="admin-nav__site"')[0]
check(site.rstrip().endswith('Notifications</a>') and 'href="/admin/?kind=addons"' in site,'the link ends the Site group of the sidebar')
check('Everything is up to date.' in page('/admin/?kind=notices') and 'Not checked yet.' in page('/admin/?kind=notices'),'the Notifications screen says so')
# ---- The server found newer versions --------------------------------------------
(sysd/'results/releases.json').write_text(json.dumps({'fetched':int(time.time()),'latest':{'version':newer,'archive':'https://github.com/x/blowfishcms.tar.gz','sha256':'https://github.com/x/blowfishcms.tar.gz.sha256','page':'https://github.com/KLD997/BlowfishCMS/releases/tag/v'+newer,'notes':''}}))
(sysd/'results/addons.json').write_text(json.dumps({'fetched':int(time.time()),'addons':[{'name':'hello','label':'Hello','version':'1.1.0','blowfishcms':'0.9.0'},{'name':'future','label':'Future','version':'2.0.0','blowfishcms':'9.0.0'}]}))
(sysd/'results/themes.json').write_text(json.dumps({'fetched':int(time.time()),'themes':[{'name':'sample','label':'Sample','version':'1.2.0','blowfishcms':'0.17.0'},{'name':'modern','label':'Modern','version':'9.0.0','blowfishcms':'0.1.0'}]}))
html=page()
check(count(html)==3,'three notices: BlowfishCMS, an add-on and a theme (not one needing a newer BlowfishCMS, nor the release’s own theme)')
toasts=html.split('class="toasts"')[1]
check(toasts.count('<div class="toast" data-toast>')==2 and f'BlowfishCMS {newer} is available' in toasts,'each shows once as a pop-up: BlowfishCMS on its own')
check('2 updates for add-ons and themes' in toasts and 'Hello 1.1.0, Sample 1.2.0' in toasts and 'value="updates_all"' in toasts,'the add-on and theme together, with “update all”')
html=page('/admin/?kind=pages')
check('class="toasts"' not in html and count(html)==3,'a pop-up isn’t shown again; the count stays')
html=page('/admin/?kind=notices')
check(html.count('<article class="theme-row">')==3 and 'href="/admin/?kind=system#release"' in html and 'Last checked' in html,'the Notifications screen lists them, each linking to where it’s updated')
cs=lambda f:run('/admin/',{'csrf':csrf,'kind':'notices',**f},cookie=alice)
check('update all add-ons and themes (2)' in html,'Notifications offers “update all” for the add-on and the theme')
html=page('/admin/?kind=themes')
check('update all themes' not in html and 'update to 1.2.0' in html,'one theme update: its own button, no “update all”')
status,_,_=run('/admin/',{'csrf':csrf,'kind':'themes','action':'themes_update_all'},cookie=alice)
req=[json.loads(p.read_text()) for p in (sysd/'requests').glob('*.json')]
check(status==303 and req and req[0]['action']=='themes_update_all' and req[0]['pins']==['theme:sample:1.2.0'],'the Themes tab’s request names only themes')
for p in (sysd/'requests').glob('*.json'):p.unlink()
status,_,hdr=cs({'action':'notice_dismiss','key':'addon:hello:1.1.0'})
check(status==303 and count(page())==2 and 'dismissed' in page('/admin/?kind=notices'),'a notice can be dismissed')
check(cs({'action':'notice_dismiss','key':'bad key!'})[0]==200,'only notice keys are accepted')
status,_,hdr=cs({'action':'updates_check'})
check(status==303 and [json.loads(p.read_text())['action'] for p in sorted((sysd/'requests').glob('*.json'))]==['updates_check'],'check now files a request for the server')
for p in (sysd/'requests').glob('*.json'):p.unlink()
# ---- One-click update ----------------------------------------------------------
html=page('/admin/?kind=system')
check(f'BlowfishCMS {newer} is available.' in html and f'value="{newer}"' in html and f'>update to {newer}</button>' in html and 'What’s new ↗' in html,'the release box offers the newer release')
sy=lambda f:run('/admin/',{'csrf':csrf,'kind':'system',**f},cookie=alice)
check('changed since this page' in sy({'action':'system_update_fetch','version':'0.0.1'})[1],'only the newest release can be asked for')
status,_,_=sy({'action':'system_update_fetch','version':newer})
req=[json.loads(p.read_text()) for p in (sysd/'requests').glob('*.json')]
check(status==303 and [(r['action'],r['arg']) for r in req]==[('update_fetch',newer)],'update to X files a request with the version')
check('Waiting for the server to start the update' in page('/admin/?kind=system'),'the progress bar shows the update waiting for the server')
for p in (sysd/'requests').glob('*.json'):p.unlink()
status,_,_=sy({'action':'system_releases_check'})
check(status==303 and [json.loads(p.read_text())['action'] for p in (sysd/'requests').glob('*.json')]==['releases_refresh'],'check for updates files a request')
for p in (sysd/'requests').glob('*.json'):p.unlink()
# ---- Email alerts ----------------------------------------------------------------
cli=lambda *a,inp=None:subprocess.run(['perl',script,*a],env=env,input=inp,capture_output=True,text=True)
pending=cli('--notices-pending').stdout
j=json.loads(pending)
check(sorted(n['key'] for n in j['notices'])==sorted(['core:'+newer,'addon:hello:1.1.0','theme:sample:1.2.0']),'the server finds the notices not emailed yet (dismissing one in the admin doesn’t stop its email)')
r=cli('--alert-mail',inp=pending)
check(r.returncode==3 and 'No alerts address' in r.stdout and not sent,'without an alerts address nothing is sent, and the notices wait')
contact=root/'var/db/bf-contact';contact.mkdir(parents=True,exist_ok=True);(contact/'mail.json').write_text(json.dumps({'alerts':'alerts@example.org','to':'owner@example.org'}))
r=cli('--alert-mail',inp=pending)
check(r.returncode==3 and 'No Postmark token' in r.stdout,'nor without a Postmark token')
sec=root/'etc/bf';sec.mkdir(parents=True,exist_ok=True);(sec/'postmark.token').write_text('good-token\n')
r=cli('--alert-mail',inp=pending)
check(r.returncode==0 and len(sent)==1 and sent[0]['To']=='alerts@example.org' and sent[0]['Subject']=='[example.org] 3 updates are available' and f'BlowfishCMS {newer} is available' in sent[0]['TextBody'] and 'https://example.org/admin/?kind=system#release' in sent[0]['TextBody'],'the alerts address gets one email listing them, with links')
check(cli('--notices-emailed').returncode==0 and cli('--notices-pending').stdout.strip()=='','once sent, they aren’t emailed again')
(sysd/'results/themes.json').write_text(json.dumps({'fetched':int(time.time()),'themes':[{'name':'sample','label':'Sample','version':'1.3.0','blowfishcms':'0.17.0'}]}))
j=json.loads(cli('--notices-pending').stdout)
check([n['key'] for n in j['notices']]==['theme:sample:1.3.0'],'a newer version is a new notice')
(sec/'postmark.token').write_text('bad-token\n')
check(cli('--alert-mail',inp=cli('--notices-pending').stdout).returncode==1,'a refused email fails, so it’s tried again')
print(json.dumps({'checks':len(checks)}))