BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
110 lines · 9.0 KB · download this file
#!/usr/bin/env python3
"""The setup walkthrough: new sites need setting up and existing ones don't;
each step saves what it asks (site details, which pages are on, the theme,
search engines); steps can be skipped; finishing leaves a to-do list on the
Overview that can be hidden; setup can be run again from Settings; editors
can't open it. Uses a fresh catalogue."""
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-setup-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)
env={**os.environ,'BLOWFISH_ROOT':str(root)}
for k in ['BLOWFISH_PAGES_SEED','BLOWFISH_ADDONS_PATH']:env.pop(k,None)
migrate=lambda:subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
migrate()
db=data/'catalog.sqlite'
def sql(q,a=()):
with signin.connect(db) as c:return c.execute(q,a).fetchall()
setting=lambda k:(sql('select value from site_settings where key=?',(k,)) or [[None]])[0][0]
def run(path,fields=None,user='alice',raw=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,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
'CONTENT_TYPE':'application/x-www-form-urlencoded','CONTENT_LENGTH':str(len(body)),'REMOTE_USER':user,'HTTP_ORIGIN':'https://example.org','HTTP_COOKIE':cookie,'REMOTE_ADDR':'192.0.2.4'}
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 if raw else H.unescape(html),hdr
cookie=''
status,_,hdr=run('/admin/');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);cookie='bf_csrf='+csrf
step=lambda name,fields:run('/admin/',{'csrf':csrf,'kind':'setup','step':name,**fields})
# ---- New and existing sites -----------------------------------------------------------
check(setting('setup')=='new','a new catalogue needs setting up')
sql("delete from site_settings where key='setup'");migrate()
check(setting('setup')=='done','a catalogue that already existed is marked as set up')
sql("update site_settings set value='new' where key='setup'")
html=run('/admin/')[1]
check('Finish setting up the site' in html and 'finishing touches' in html,'the Overview links to the setup until it\'s done')
# ---- The steps ---------------------------------------------------------------------------
status,html,_=run('/admin/?kind=setup')
check(status==200 and '<h1>Set up your site</h1>' in html and 'aria-current="step">Your site' in html,'the setup opens on the first step')
check('Give the site a name' in step('basics',{'action':'setup_basics','site_title':' ','author':'','description':''})[1],'the site needs a name')
status,_,hdr=step('basics',{'action':'setup_basics','site_title':'Harbour Notes','author':'A. Writer','description':'Notes from the harbour.'})
check(status==303 and hdr['Location'].endswith('step=pages') and setting('site_title')=='Harbour Notes','the site details are saved and the next step opens')
html=run('/admin/?kind=setup&step=pages')[1]
pages=re.findall(r'name="on" value="([^"]+)"',html)
check('home' in pages and 'contact' in pages and re.search(r'value="home" checked disabled',html),'every page is listed; Home is always on')
step('pages',{'action':'setup_pages','on':[]})
nav={i['page']:i['visible'] for i in json.loads(setting('nav'))}
check(nav['home']==1 and nav['contact']==0,'the chosen pages are on and the rest off (Home always)')
check(run('/contact/',user='')[0]==404 and run('/',user='')[0]==200,'pages left off answer “not found” to visitors')
step('pages',{'action':'setup_pages','on':['contact']})
themes=re.findall(r'name="theme" value="([^"]+)"',run('/admin/?kind=setup&step=look')[1])
check(len(themes)>=2,'the look step lists the enabled themes')
check('Choose one of the themes' in step('look',{'action':'setup_look','theme':'nope'})[1],'only real themes are taken')
step('look',{'action':'setup_look','theme':themes[-1]})
check(setting('default_theme')==themes[-1],'the chosen theme becomes the default')
step('search',{'action':'setup_search','search_visible':'0','entity_type':'organization'})
check(setting('search_visible')=='0' and setting('entity_type')=='organization','search engine choices are saved')
check('<meta name="robots" content="noindex' in run('/',user='')[1] or 'noindex' in run('/',user='')[1],'a site kept out of search says so to search engines')
html=run('/admin/?kind=setup&step=mail')[1]
check('href="/admin/mail/"' in html and 'type="password"' not in html and 'name="token"' not in html,'the mail step sends you to the Mail screen for the token (it never asks for it)')
status,_,hdr=step('mail',{'action':'setup_skip'})
check(status==303 and hdr['Location'].endswith('step=addons'),'steps can be skipped')
check('Add-ons' in run('/admin/?kind=setup&step=addons')[1],'the add-ons step explains add-ons')
status,_,hdr=step('done',{'action':'setup_finish'})
check(status==303 and setting('setup')=='done','finishing marks the site as set up')
# ---- The finishing touches ----------------------------------------------------------------
html=run('/admin/')[1]
check('Finish setting up' not in html and 'Give the site its own favicon' in html and 'Describe the site' not in html,'the Overview lists what\'s left, not what\'s done')
status,_,_=run('/admin/',{'csrf':csrf,'kind':'setup','action':'setup_todo_hide'})
check(status==303 and 'finishing touches' not in run('/admin/')[1],'the list can be hidden')
# ---- The footer and the look on the site ---------------------------------------------------
year=str(__import__('datetime').datetime.now(__import__('datetime').timezone.utc).year)
check(setting('footer_text')=='© {year} · {site}' and f'© {year} · Harbour Notes' in run('/',user='')[1],'a new site\'s footer is a copyright line with this year and the site name')
sql("update site_settings set value='<b>Bold</b> & Co' where key='site_title'")
foot=run('/',user='',raw=True)[1].split('</main>')[-1]
check('· <b>Bold</b> & Co' in foot and '<b>Bold</b>' not in foot,'the site name in the footer is plain text')
sql("update site_settings set value='Harbour Notes' where key='site_title'")
home=run('/',user='')[1]
check('id="theme-picker"' in home and '"picker":true' in home and 'data-window-bars' not in home,'by default visitors can choose a theme and sections have title bars')
status,_,_=run('/admin/',{'csrf':csrf,'kind':'themes','action':'theme_site_options'})
home=run('/',user='')[1]
check(status==303 and 'id="theme-picker"' not in home and '"picker":false' in home and 'data-window-bars="off"' in home,'the theme menu and title bars can be turned off')
run('/admin/',{'csrf':csrf,'kind':'themes','action':'theme_site_options','theme_picker':'1','window_bars':'1'})
check('id="theme-picker"' in run('/',user='')[1],'and on again')
# ---- Again, and editors ------------------------------------------------------------------------
check('Run the setup questions again</button>' in (h:=run('/admin/?kind=settings')[1]) and '</span>setup</div>' not in h and '</span>pictures</div>' not in h and '</span>pictures</div>' in run('/admin/?kind=branding')[1],'Settings offers to run the setup again; the site’s pictures are under Look')
status,_,hdr=run('/admin/',{'csrf':csrf,'kind':'setup','action':'setup_restart'})
check(status==303 and setting('setup')=='new' and 'step=basics' in hdr['Location'],'running it again starts from the first step')
h=subprocess.run(['perl','-e','print crypt($ARGV[0],"\\$2b\\$10\\$".join("",map {("a".."z")[rand 26]} 1..22))','bob password one'],capture_output=True,text=True).stdout
sql("insert into admin_users(name,email,role,hash,created_at) values ('bob','','editor',?,'2026-01-01')",(h,))
check(run('/admin/?kind=setup',user='bob')[0]==403 and run('/admin/',{'csrf':csrf,'kind':'setup','action':'setup_finish'},user='bob')[0]==403,'editors can\'t open the setup')
check('kind=setup' not in run('/admin/',user='bob')[1],'editors don\'t see the setup link')
print(json.dumps({'checks':len(checks)}))