repository

BlowfishCMS

A small content management system for OpenBSD

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

159 lines · 15.3 KB · download this file

#!/usr/bin/env python3
"""Admin users: the install's admin account becomes the first owner; owners
add editors and other owners; editors can't open the owners' sections (in the
admin, the Mail screen or add-on screens); passwords, removal and "sign out
everywhere" end sessions in every service; the site always keeps an owner;
`site.pl --set-password` (blowfishctl password) works from the server. Uses a
fresh catalogue; never touches live data."""
import html as H
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,time
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-users-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)
 db=data/'catalog.sqlite'
 acc=data/'admin/accounts.sqlite'
 def accounts(q,a=()):
  with signin.connect(acc) as c:return c.execute(q,a).fetchall()
 def sql(q,a=()):
  with signin.connect(db) as c:return c.execute(q,a).fetchall()
 def run(path,fields=None,cookie='',fetch=False,script_name=None,ip='192.0.2.7'):
  url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {}).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':script_name or url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
     'CONTENT_TYPE':'application/x-www-form-urlencoded','CONTENT_LENGTH':str(len(body)),'REMOTE_USER':'','HTTP_ORIGIN':'https://example.org','HTTP_COOKIE':cookie,'REMOTE_ADDR':ip,**({'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
 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,ip='192.0.2.7'):
  status,_,hdr=run('/admin/',{'csrf':csrf,'kind':'login','user':user,'password':password,'next':'/admin/'},cookie='bf_csrf='+csrf,ip=ip)
  s=cookie_of(hdr,'bf_session');return f'bf_csrf={csrf}; bf_session={s}' if status==303 and s else None
 def act(ck,kind,fields,**o):
  import html as H
  status,body,hdr=run('/admin/',{'csrf':csrf,'kind':kind,**fields},cookie=ck,**o);return status,H.unescape(body),hdr
 def signed_in(ck):
  status,html,_=run('/admin/',cookie=ck);return status==200 and 'name="password"' not in html and '<h1>Overview</h1>' in html

 # ---- The first owner ----------------------------------------------------------------
 check(sql('select name,role from admin_users')==[('alice','owner')],'the install\'s admin account becomes the first owner')
 alice=sign_in('alice','alice password one')
 check(alice and signed_in(alice),'the owner signs in with the password they had')
 status,html,_=run('/admin/?kind=users',cookie=alice)
 check(status==200 and '<h2>alice <span class="media-label">(you)</span></h2>' in html and 'href="/admin/?kind=users"' in html,'owners see Users')
 check('id="add-user"><h3>Add a user</h3>' in html and '</span>add a user</div>' not in html,'adding a user is at the foot of the users box')

 # ---- Adding users ------------------------------------------------------------------
 add=lambda **f:act(alice,'users',{'action':'user_add','email':'','role':'editor',**f})
 check('at least 12' in add(name='bob',password='short',password2='short')[1],'short passwords are refused')
 check('don\'t match' in add(name='bob',password='bob password one',password2='bob password two')[1],'mistyped passwords are refused')
 check('Names are' in add(name='Bob Smith',password='bob password one',password2='bob password one')[1],'names must be login names')
 check('look right' in add(name='bob',email='not an address',password='bob password one',password2='bob password one')[1],'email addresses are checked')
 status,_,hdr=add(name='bob',email='bob@example.org',password='bob password one',password2='bob password one')
 check(status==303 and sql("select role from admin_users where name='bob'")==[('editor',)] and accounts("select email from accounts where name='bob'")==[('bob@example.org',)],'an owner adds an editor')
 check(accounts("select hash from accounts where name='bob'")[0][0].startswith('$2b$10$'),'passwords are stored as bcrypt')
 check(sql("select count(*) from admin_users where hash<>'' or email<>''")==[(0,)] and oct(acc.stat().st_mode&0o777)=='0o600','passwords and email addresses are only in the admin service\'s own file (0600), not in the catalogue other services read')
 check('bob@example.org' in run('/admin/?kind=users',cookie=alice)[1],'the Users screen shows their email address')
 menu=re.search(r'aria-label="More for bob">…</summary><div class="row-menu__items">(.*?)</details>',run('/admin/?kind=users',cookie=alice)[1],re.S)
 check(menu and 'value="user_remove"' in menu.group(1),'removing a user is in their row’s “…” menu')
 check(re.search(r'<form method="post" action="/admin/" class="inline-form" data-auto-submit>[^<]*<input type="hidden" name="action" value="user_role"',run('/admin/?kind=users',cookie=alice)[1]) is not None,'a user’s role applies as soon as it’s chosen')
 check('already a user' in add(name='bob',password='bob password one',password2='bob password one')[1],'names are unique')

 # ---- What editors can do --------------------------------------------------------------
 bob=sign_in('bob','bob password one')
 check(bob and signed_in(bob),'an editor signs in')
 html=run('/admin/',cookie=bob)[1];nav=re.search(r'<nav class="admin-nav".*?</nav>',html,re.S).group(0)
 check('kind=pages' in nav and 'kind=photography' in nav and '/admin/comments/' in nav and all(x not in nav for x in ['kind=settings','kind=users','kind=themes','kind=branding','kind=search','/admin/mail/','kind=addons']),'editors see the content in the sidebar, not the site settings')
 for kind in ['settings','users','themes','branding','search','addons','system','x-store']:
  check(run('/admin/?kind='+kind,cookie=bob)[0]==403,'editors can\'t open '+kind)
 check(act(bob,'settings',{'action':'settings_save','site_title':'Taken over'})[0]==403 and sql("select count(*) from site_settings where value='Taken over'")==[(0,)],'editors can\'t change settings')
 check(act(bob,'users',{'action':'user_add','name':'mallory','role':'owner','password':'mallory password','password2':'mallory password'})[0]==403 and not sql("select * from admin_users where name='mallory'"),'editors can\'t add users')
 check(run('/admin/mail/',cookie=bob,script_name='/admin/mail/')[0]==403,'editors can\'t open the Mail screen (its own service)')
 check(run('/admin/comments/',cookie=bob,script_name='/admin/comments/')[0]==200,'editors moderate comments')
 check(run('/admin/?kind=pages',cookie=bob)[0]==200 and run('/admin/?kind=photography',cookie=bob)[0]==200 and run('/admin/?kind=blog',cookie=bob)[0]==200,'editors manage pages, pictures and articles')
 check(run('/admin/mail/',cookie=alice,script_name='/admin/mail/')[0]==200 and run('/admin/?kind=settings',cookie=alice)[0]==200,'owners open everything')

 # ---- Roles and the last owner ---------------------------------------------------------
 check(act(alice,'users',{'action':'user_role','name':'bob','role':'owner'})[0]==303 and run('/admin/?kind=settings',cookie=bob)[0]==200,'an editor made an owner can open the settings at once')
 act(alice,'users',{'action':'user_role','name':'bob','role':'editor'})
 check(run('/admin/?kind=settings',cookie=bob)[0]==403,'and loses them when made an editor again')
 check('at least one owner' in act(alice,'users',{'action':'user_role','name':'alice','role':'editor'})[1],'the last owner can\'t become an editor')
 check('remove yourself' in act(alice,'users',{'action':'user_remove','name':'alice'})[1] or 'at least one owner' in act(alice,'users',{'action':'user_remove','name':'alice'})[1],'the last owner can\'t be removed')

 # ---- Passwords and sessions -------------------------------------------------------------
 bob_laptop=sign_in('bob','bob password one',ip='192.0.2.8')
 act(alice,'users',{'action':'user_password','name':'bob','password':'bob password two','password2':'bob password two'})
 check(not signed_in(bob) and not signed_in(bob_laptop) and signed_in(alice),'an owner setting a new password signs that user out everywhere, and only them')
 check(sign_in('bob','bob password one') is None and (bob:=sign_in('bob','bob password two')),'the old password stops working; the new one works')
 bob_laptop=sign_in('bob','bob password two',ip='192.0.2.8')
 check('isn\'t right' in act(bob,'account',{'action':'account_password','current':'wrong','password':'bob password three','password2':'bob password three'})[1],'changing your own password needs the current one')
 
 status,_,hdr=act(bob,'account',{'action':'account_password','current':'bob password two','password':'bob password three','password2':'bob password three'})
 bob=f'bf_csrf={csrf}; bf_session={cookie_of(hdr,"bf_session")}'
 check(status==303 and signed_in(bob) and not signed_in(bob_laptop),'changing your own password keeps this browser signed in and signs out the others')
 check(act(bob,'account',{'action':'account_email','email':'bob@example.net'})[0]==303 and accounts("select email from accounts where name='bob'")==[('bob@example.net',)],'users change their own email address')
 
 bob_laptop=sign_in('bob','bob password three',ip='192.0.2.8')
 
 act(bob,'logout',{'everywhere':'1'})
 check(not signed_in(bob) and not signed_in(bob_laptop) and signed_in(alice),'sign out everywhere ends only your own sessions')

 # ---- Removing users --------------------------------------------------------------------
 bob=sign_in('bob','bob password three')
 check(act(alice,'users',{'action':'user_remove','name':'bob'})[0]==303 and not signed_in(bob) and sign_in('bob','bob password three') is None,'a removed user is signed out and can\'t sign in')
 check(run('/talk/comment',{'item':'0'*32,'name':'Alice','body':'hi'})[0] in (303,404),'comments still answer')

 # ---- Settings › Sign-in (0.27) ---------------------------------------------------------------
 act(alice,'users',{'action':'user_add','name':'erin','email':'','role':'editor','password':'erin password one','password2':'erin password one'})
 erin=sign_in('erin','erin password one')
 tabs=re.search(r'<nav class="admin-tabs" aria-label="Settings">(.*?)</nav>',run('/admin/?kind=users',cookie=alice)[1],re.S).group(1)
 check(re.findall(r'href="([^"]+)"',tabs)==['/admin/?kind=settings','/admin/?kind=search','/admin/mail/','/admin/?kind=users','/admin/?kind=signin','/admin/?kind=system'],'Users and Sign-in are tabs of Settings')
 side=run('/admin/?kind=users',cookie=alice)[1].split('<div class="admin-main">')[0]
 check('kind=users' not in side and 'aria-current="page">Settings' in side and 'kind=account' in side,'they left the sidebar, where Settings is marked; your account stays there')
 check(run('/admin/?kind=signin',cookie=erin)[0]==403,'editors can\'t open Sign-in')
 act(alice,'signin',{'action':'signin_unlock'})
 for _ in range(2):sign_in('alice','not the password',ip='192.0.2.40')
 html=H.unescape(run('/admin/?kind=signin',cookie=alice)[1])
 check(re.search(r'<strong>2</strong> failed sign-ins from 1 place',html) and 'name="mfa_required"' in html,'Sign-in shows the last hour\'s failed sign-ins and who must use two-step sign-in')
 for _ in range(3):sign_in('alice','not the password',ip='192.0.2.40')
 check(sign_in('alice','alice password one',ip='192.0.2.40') is None,'five wrong passwords lock that place')
 check('1 place is locked out' in H.unescape(run('/admin/?kind=signin',cookie=alice)[1]),'Sign-in says a place is locked out')
 check(act(alice,'signin',{'action':'signin_unlock'})[0]==303 and sign_in('alice','alice password one',ip='192.0.2.40'),'unlock clears failed sign-ins, as blowfishctl unlock does')
 status,_,hdr=act(alice,'signin',{'action':'signin_everyone_out'})
 fresh=cookie_of(hdr,'bf_session')
 check(status==303 and not signed_in(erin) and not signed_in(alice) and fresh and signed_in(f'bf_csrf={csrf}; bf_session={fresh}'),'sign everyone out ends every session; the owner who pressed it gets a fresh one')
 alice=f'bf_csrf={csrf}; bf_session={fresh}'
 check(act(erin,'signin',{'action':'signin_everyone_out'})[0] in (303,401,403),'editors can\'t sign everyone out')
 # ---- From the server: blowfishctl password -----------------------------------------------
 def set_pw(name,pw):return subprocess.run(['perl',script,'--set-password',name],input=bcrypt(pw),env=env,capture_output=True,text=True)
 out=set_pw('carol','carol password one')
 check(out.returncode==0 and 'Added carol as an owner' in out.stdout and sql("select role from admin_users where name='carol'")==[('owner',)],'a name that isn\'t a user yet becomes an owner (a way back in)')
 carol=sign_in('carol','carol password one');
 out=set_pw('carol','carol password two')
 check(out.returncode==0 and not signed_in(carol) and sign_in('carol','carol password two'),'setting an existing user\'s password ends their sessions')
 check(subprocess.run(['perl',script,'--set-password','carol'],input='not a hash',env=env,capture_output=True,text=True).returncode!=0,'only a bcrypt hash is accepted')
 check(subprocess.run(['perl',script,'--set-password','Bad Name'],input=bcrypt('x'*12),env=env,capture_output=True,text=True).returncode!=0,'only login names are accepted')
 # The update's check of a site's own data works on a site with its own admin users.
 r=subprocess.run([sys.executable,str(pathlib.Path(__file__).resolve().parent/'upgrade.py'),sys.argv[1]],env={**os.environ,'BLOWFISH_TEST_CATALOG':str(db)},capture_output=True,text=True)
 check(r.returncode==0 and 'kind=search opens' in r.stdout,'tests/upgrade.py passes on a site with its own owners and editors'+('' if r.returncode==0 else ': '+(r.stderr.strip().splitlines() or ['?'])[-1]))
print(json.dumps({'checks':len(checks)}))