BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
155 lines · 15.3 KB · download this file
#!/usr/bin/env python3
"""The picture library: folders that are real directories on disk, and
renaming and moving that keep articles, pages and galleries working. Uses a
temporary site; never touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,struct,zlib
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 png(width=48,height=32):
def chunk(k,d):return struct.pack('>I',len(d))+k+d+struct.pack('>I',zlib.crc32(k+d)&0xffffffff)
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress((b'\0'+bytes([30,100,140])*width)*height))+chunk(b'IEND',b'')
with tempfile.TemporaryDirectory(prefix='blowfish-pictures-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))
media=root/'media/bf'
for kind in ['photography','music','artwork','blog','video']:(media/kind).mkdir(parents=True)
env={**os.environ,'BLOWFISH_ROOT':str(root)}
env['BLOWFISH_PAGES_SEED']=str(pathlib.Path(__file__).resolve().parent/'fixtures/basic-site-pages.json')
migrate=lambda:subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
migrate()
db=data/'catalog.sqlite'
def sql(q,args=()):
with signin.connect(db) as c:return c.execute(q,args).fetchall()
def run(path,fields=None,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:
boundary='bftest'+secrets.token_hex(8);parts=[]
for k,v in (fields or {}).items():
for one in (v if isinstance(v,list) else [v]):parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{one}\r\n'.encode())
for name,filename,blob 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()+blob+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,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
'CONTENT_TYPE':ctype,'CONTENT_LENGTH':str(len(body)),'REMOTE_USER':'alice' if url.path.startswith('/admin') else '','HTTP_ORIGIN':'https://example.org','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
cookie=''
status,_,hdr=run('/admin/');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);cookie='bf_csrf='+csrf
adm=lambda fields,**o:run('/admin/',{'csrf':csrf,'kind':'photography',**fields},**o)
pics=media/'pictures'
# ---- A library: folders, pictures, an article and blocks that show them ----------------
check(pics.is_dir() and sql("select value from site_settings where key='pictures_version'")==[('4',)] and sql("select hidden from picture_folders where path='site'")==[(1,)],'a new site starts with the picture library and its Site folder, kept out of galleries')
for path,name in [('travel','Travel'),('travel/japan','Japan'),('articles','Articles'),('pages','Pages')]:
(pics/path).mkdir(parents=True,exist_ok=True);sql("insert into picture_folders (path,name,created_at) values (?,?,'2026-01-01T00:00:00Z')",(path,name))
def picture(title,folder,w=48,h=32,thumb=True):
i=secrets.token_hex(16);f=i+'.png';(pics/folder/f).write_bytes(png(w,h))
t=i+'-thumb.png' if thumb else ''
if thumb:(pics/folder/t).write_bytes(png(24,16))
sql("insert into uploads (id,kind,title,folder,filename,thumbnail,mime,bytes,width,height,created_at,sort_order) values (?,'photography',?,?,?,?,'image/png',100,?,?,'2026-01-01T00:00:00Z',0)",(i,title,folder,f,t,w,h))
return i,f
old={t:picture(t,f)[0] for t,f in [('Shrine','travel/japan'),('Harbour','travel'),('Loose','')]}
art_id,inline=picture('From “Trip notes”','articles',60,40,False)
own_id,own=picture('A square','pages',80,60,False)
pp,portrait=picture('Portrait','pages',64,64,False)
post=secrets.token_hex(16)
sql("insert into posts (id,title,body,published_at,created_at,updated_at) values (?,?,?,?,?,?)",(post,'Trip notes',f' twice ','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z'))
blocks={'own':('picture_text',{'title':'about','heading':'Hi','body':'Text','picture':own_id,'alt':'A square','position':'right','picture_size':'small'}),
'portrait':('about',{'title':'about','heading':'Me','body':'Bio','picture':pp,'position':''}),
'g_one':('gallery',{'title':'photos','source':'folder','folder':'travel/japan','subfolders':0,'layout':'grid','captions':1}),
'g_all':('gallery',{'title':'photos','source':'folder','folder':'','subfolders':1,'layout':'grid','captions':1})}
bid={}
for n,(k,(t,d)) in enumerate(blocks.items()):
bid[k]=secrets.token_hex(8);sql('insert into page_blocks (id,page,sort_order,type,width,data) values (?,?,?,?,?,?)',(bid[k],'home',90+n,t,'full',json.dumps(d)))
migrate()
block=lambda k:(lambda r:(r[0],json.loads(r[1])))(sql('select type,data from page_blocks where id=?',(bid[k],))[0])
html=run('/')[1]
check(f'src="/media/pictures/pages/{own}" alt="A square"' in html and 'Shrine' in html and f'src="/media/pictures/pages/{portrait}"' in html,'blocks show pictures from the library')
html=run('/blog/?post='+post)[1]
check(f'src="/media/pictures/articles/{inline}"' in html,'the article shows its picture from the library')
# ---- The Pictures screen ------------------------------------------------------------
status,html,_=run('/admin/?kind=photography')
check(status==200 and 'href="/admin/?kind=photography&folder=travel"' in html and 'folder-tile' in html and html.count('<li class="lib-item"')==1,'the top level lists its folders and only its own pictures')
status,html,_=run('/admin/?kind=photography&folder=travel%2Fjapan')
check('aria-current="page">Japan<' in html and '>Travel</a>' in html and 'Shrine' in html and 'Harbour' not in html,'a folder shows its breadcrumbs and its pictures')
check(run('/admin/?kind=photography&folder=..%2F..%2Fetc')[0]==200 and 'Shrine' not in run('/admin/?kind=photography&folder=..%2F..%2Fetc')[1],'an invalid folder shows the top level')
status,_,hdr=adm({'action':'folder_create','folder':'travel','name':'Night Shots!'})
check(status==303 and 'folder=travel%2Fnight-shots' in hdr['Location'] and (pics/'travel/night-shots').is_dir(),'a new folder is a directory on disk, with an address-safe name')
check('already a folder' in adm({'action':'folder_create','folder':'travel','name':'night shots'})[1],'two folders with the same address are refused')
check('no longer exists' in adm({'action':'folder_create','folder':'../x','name':'Bad'})[1] and not (pics.parent/'x').exists(),'a folder outside the library is refused')
deep='travel'
for name in 'abcd':deep=re.search(r'folder=([^&]+)',adm({'action':'folder_create','folder':deep,'name':name})[2]['Location']).group(1).replace('%2F','/')
check(deep=='travel/a/b/c/d' and 'five deep' in adm({'action':'folder_create','folder':deep,'name':'e'})[1],'folders nest up to five deep')
# Upload into a folder.
status,html,_=run('/admin/',{'csrf':csrf,'kind':'photography','action':'upload','folder':'travel/night-shots'},files=[('media','moon.png',png(64,40))])
moon=sql("select id,folder,filename,thumbnail from uploads where title='moon'")[0]
check(moon[1]=='travel/night-shots' and (pics/'travel/night-shots'/moon[2]).exists() and (pics/'travel/night-shots'/moon[3]).exists(),'an upload goes into the folder being viewed, on disk too')
check('no longer exists' in run('/admin/',{'csrf':csrf,'kind':'photography','action':'upload','folder':'nowhere'},files=[('media','x.png',png())])[1] and not sql("select * from uploads where title='x'"),'an upload into a missing folder is refused')
# Move the article's picture into a folder: the article follows.
art=sql("select id,filename from uploads where folder='articles'")[0]
status,body,_=adm({'action':'bulk','op':'folder','folder':'travel/japan','ids':[art[0]]},fetch=True)
check(status==200 and (pics/'travel/japan'/art[1]).exists() and not (pics/'articles'/art[1]).exists(),'moving a picture moves its file')
check(f'/media/pictures/travel/japan/{art[1]}' in sql('select body from posts where id=?',(post,))[0][0],'an article showing a moved picture is rewritten')
# Rename a folder with pictures and a subfolder: the directory, pictures and articles follow.
status,_,hdr=adm({'action':'folder_rename','folder':'travel','name':'Trips 2024'})
check(status==303 and (pics/'trips-2024/japan'/art[1]).exists() and not (pics/'travel').exists(),'renaming a folder renames its directory, subfolders included')
check(dict(sql("select title,folder from uploads where kind='photography'"))['Shrine']=='trips-2024/japan' and ('trips-2024/a/b/c/d',) in sql('select path from picture_folders'),'pictures and subfolders follow the rename')
check(f'/media/pictures/trips-2024/japan/{art[1]}' in sql('select body from posts where id=?',(post,))[0][0] and f'src="/media/pictures/trips-2024/japan/{art[1]}"' in run('/blog/?post='+post)[1],'articles follow the rename')
check(dict(sql('select path,name from picture_folders'))['trips-2024']=='Trips 2024','the folder keeps its name as typed')
# Delete.
check('first' in adm({'action':'folder_delete','folder':'trips-2024/japan'})[1],'a folder with pictures is not deleted')
status,_,hdr=adm({'action':'folder_delete','folder':'trips-2024/a'})
check(status==303 and not (pics/'trips-2024/a').exists() and not sql("select * from picture_folders where path like 'trips-2024/a%'"),'an empty folder (with empty subfolders) is deleted, directories too')
html=run('/admin/?kind=photography&folder=trips-2024%2Fjapan')[1]
check('data-confirm="This picture is shown on the article “Trip notes”' in html,'deleting a picture an article shows asks first')
status,body,_=adm({'action':'bulk','op':'delete','ids':[moon[0]]},fetch=True)
check(status==200 and not (pics/'trips-2024/night-shots'/moon[2]).exists() and not (pics/'trips-2024/night-shots'/moon[3]).exists(),'deleting a picture removes its files')
# ---- Choosing from the library for the logo, favicon and share picture -------------------
run('/admin/',{'csrf':csrf,'kind':'photography','action':'upload','folder':''},files=[('media','wide.png',png(800,420))])
pid=sql("select id from uploads where kind='photography' and title='wide'")[0][0]
site=lambda kind,action:run('/admin/',{'csrf':csrf,'kind':kind,'action':action,'picture':pid})
for kind,action,key,name in [('branding','logo_upload','logo','logo-{}.png'),('branding','favicon_upload','favicon','icon-{}-180.png'),('settings','share_upload','share_image','share-{}.jpg')]:
status,_,_=site(kind,action);made=sql('select value from site_settings where key=?',(key,))
check(status==303 and made and (media/'site'/name.format(made[0][0])).exists(),f'the {key.replace("_"," ")} can be chosen from Pictures (a copy is made)')
check('or choose from Pictures' in run('/admin/?kind=branding')[1].replace('data-choose-into hidden','data-choose-into'),'Logo & icons offers “choose from Pictures”')
check('no longer in the library' in run('/admin/',{'csrf':csrf,'kind':'settings','action':'logo_upload','picture':'0'*32})[1],'a picture that isn\'t in the library is refused')
# ---- Keeping pictures out of galleries ---------------------------------------------
check(sql("select name,hidden from picture_folders where path='site'")==[('Site',1)] and (pics/'site').is_dir(),'a Site folder, kept out of galleries, is made')
pp=block('portrait')[1]['picture']
status,_,hdr=adm({'action':'picture_gallery','id':pp,'hidden':'1'})
check(status==303 and sql('select gallery_hidden from uploads where id=?',(pp,))==[(1,)],'the eye keeps a picture out of galleries')
shown=lambda name:run('/')[1].count(name)
before=shown(portrait)
html=run('/admin/?kind=photography&folder=pages')[1]
check('title="Kept out of galleries: click to show it in galleries"' in html and 'value="picture_gallery"' in html and 'class="lib-thumb__hidden" title="Kept out of galleries"' in html,'a kept-out picture has a crossed eye on its card and in its panel')
adm({'action':'item_save','id':pp,'title':'Portrait','folder':'pages','description':''},fetch=True)
check(sql('select gallery_hidden from uploads where id=?',(pp,))==[(1,)],'saving its title and description leaves that alone')
status,_,hdr=adm({'action':'picture_gallery','id':pp,'hidden':'0'})
after=shown(portrait)
check(status==303 and hdr['Location'].endswith('#edit-'+pp) and sql('select gallery_hidden from uploads where id=?',(pp,))==[(0,)] and after>before,'the eye puts it back in the gallery of everything')
check('title="Shown in galleries: click to keep it out of them"' in run('/admin/?kind=photography&folder=pages')[1],'and then shows open')
adm({'action':'picture_gallery','id':pp,'hidden':'1'})
check(shown(portrait)==before,'pressed again, it takes it out; the About me block still shows it')
sf,sfolder=sql("select filename,folder from uploads where title='Shrine'")[0];top=sfolder.split('/')[0];shrine=shown(sf)
status,_,hdr=adm({'action':'folder_hide','folder':top,'hidden':'1'})
check(status==303 and sql("select hidden from picture_folders where path=?",(top,))==[(1,)] and 0<shown(sf)<shrine,'a folder kept out of galleries leaves the gallery of everything, with its subfolders; a gallery of that folder itself still shows it')
check('title="Kept out of galleries: click to show this folder in galleries"' in run('/admin/?kind=photography&folder='+top)[1] and 'title="Kept out of galleries, because a folder above it is"' in run('/admin/?kind=photography&folder='+sfolder)[1],'the folder’s eye says so, and its subfolders’ say why')
adm({'action':'folder_hide','folder':top,'hidden':'0'})
check(shown(sf)==shrine,'and it can be shown again')
html=run('/admin/?kind=photography&folder='+top)[1]
top_bar=html.split('<main')[0]
check('title="Shown in galleries: click to keep this folder out of them"' in top_bar and 'new folder</summary>' in top_bar and 'data-upload-input' in top_bar and 'upload pictures</label>' in top_bar and 'aria-label="Folder options"' in top_bar and 'Galleries show this folder' not in html and 'folder-tools' not in html,'the folder’s eye and options are icons at the top right; new folder and upload pictures are labelled buttons')
check('class="lib-upload lib-upload--quiet"' in html and 'aria-label="Folder options"' not in run('/admin/?kind=photography')[1].split('<main')[0],'the upload box only shows while uploading; the top folder has no options')
print(json.dumps({'checks':len(checks)}))