repository

BlowfishCMS

A small content management system for OpenBSD

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

138 lines · 11.3 KB · download this file

#!/usr/bin/env python3
"""The Files library: uploads of any kind in pieces, their size and sha256,
where they're stored, their pages, the Download block, download counting
(/download/ID/, nothing about the visitor kept) and removal. Runs on a new
site's catalogue; never touches live data or media."""
import sys,pathlib;sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import start_catalog
import os,tempfile,sqlite3,subprocess,json,re,urllib.parse,secrets,hashlib
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-files-test-') as tmp:
 root=pathlib.Path(tmp);data=root/'var/db/blowfishcms';(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/blowfishcms'/kind).mkdir(parents=True)
 start_catalog(data/'catalog.sqlite')
 env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json')}
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.DEVNULL)
 con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
 cols=[r['name'] for r in con.execute('pragma table_info(uploads)')]
 check('version' in cols and 'sha256' in cols,'uploads have version and sha256')
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.DEVNULL)
 check(True,'the migration can run twice')
 cookie=''
 def run(path,fields=None,files=(),fetch=True,user='admin',script_name=None,ua='Mozilla/5.0 (X11; Linux x86_64) Firefox/140.0',method=None):
  global cookie
  url=urllib.parse.urlsplit(path);body=b'';ctype='application/x-www-form-urlencoded'
  if fields is not None:
   if files:
    b='---'+secrets.token_hex(12);parts=[]
    for k,v in fields.items():parts.append(f'--{b}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
    for k,name,mime,content in files:parts.append(f'--{b}\r\nContent-Disposition: form-data; name="{k}"; filename="{name}"\r\nContent-Type: {mime}\r\n\r\n'.encode()+content+b'\r\n')
    body=b''.join(parts)+f'--{b}--\r\n'.encode();ctype='multipart/form-data; boundary='+b
   else:body=urllib.parse.urlencode(fields,doseq=True).encode()
  e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':method or ('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':ctype,'CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':cookie,'REMOTE_USER':user,'HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':'192.0.2.1','HTTP_USER_AGENT':ua}
  if fetch:e['HTTP_X_REQUESTED_WITH']='fetch'
  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('utf-8','replace').split('\r\n\r\n',1);hdr=dict(l.split(': ',1) for l in head.split('\r\n'))
  if 'Set-Cookie' in hdr and hdr['Set-Cookie'].startswith('bf_csrf='):cookie=hdr['Set-Cookie'].split(';')[0]
  return int(hdr['Status']),html,hdr
 run('/admin/?kind=file',fetch=False)
 csrf=cookie.split('=',1)[1]
 def act(action,files=(),**f):
  s,body,_=run('/admin/',{'csrf':csrf,'kind':'file','action':action,**f},files=files)
  return s,json.loads(body)
 def upload(name,content,piece=65536,**meta):
  s,r=act('upload_start',name=name,size=str(len(content)),**meta);assert s==200,r;uid=r['upload']
  for off in range(0,len(content),piece):
   s,r=act('upload_chunk',files=[('chunk','piece','application/octet-stream',content[off:off+piece])],upload=uid,offset=str(off));assert s==200,r
  return act('upload_finish',upload=uid)
 files_dir=root/'media/blowfishcms/file'

 # ---- Before the setup step: no files folder ---------------------------------
 s,r=act('upload_start',name='a.zip',size='10')
 check(s==400 and 'server setup' in r['message'],'missing files folder explained')
 files_dir.mkdir()

 # ---- The screen ----------------------------------------------------------------
 s,html,_=run('/admin/?kind=file',fetch=False)
 check(s==200 and 'Files' in html and 'data-exts=""' in html and '<a href="/admin/?kind=file"' in html,'the Files screen is in the sidebar and takes any kind of file')
 check(act('upload_start',name='empty.bin',size='0')[0]==400,'empty file refused')
 check('2 GB or smaller' in act('upload_start',name='big.iso',size=str(2*1024**3+1))[1]['message'],'files over 2 GB refused before uploading')

 # ---- Uploading: pieces, resume, any kind ----------------------------------------
 release=os.urandom(200_000)
 s,r=act('upload_start',name='BlowfishCMS 1.0 (final).tar.gz',size=str(len(release)),collection='Releases',description='The first release')
 uid=r['upload']
 act('upload_chunk',files=[('chunk','p','application/octet-stream',release[:65536])],upload=uid,offset='0')
 s,r=act('upload_status',upload=uid);check(r['received']==65536,'an interrupted upload says how much arrived')
 for off in range(65536,len(release),65536):act('upload_chunk',files=[('chunk','p','application/octet-stream',release[off:off+65536])],upload=uid,offset=str(off))
 s,r=act('upload_finish',upload=uid);check(s==200,'a file uploads in pieces and resumes')
 row=con.execute("select * from uploads where kind='file'").fetchone()
 fid=row['id']
 check(row['sha256']==hashlib.sha256(release).hexdigest() and row['bytes']==len(release),'its size and sha256 are worked out on upload')
 check(row['filename']==fid+'/BlowfishCMS-1.0-final.tar.gz' and (files_dir/fid/'BlowfishCMS-1.0-final.tar.gz').read_bytes()==release,'stored unchanged in a folder of its own, under a cleaned name')
 check(row['title']=='BlowfishCMS 1.0 (final)' and row['collection']=='Releases','title and collection from the upload')
 check(not list((data/'admin/tmp').glob('upload-*')),'nothing left behind in the upload folder')
 s,r=upload('../../etc/passwd',b'not really')
 evil=con.execute("select * from uploads where kind='file' and title like 'passwd%'").fetchone()
 check(s==200 and evil['filename']==evil['id']+'/passwd' and (files_dir/evil['id']/'passwd').exists(),'a name with a path is cut to its last part')
 s,r=upload('page.html',b'<script>alert(1)</script>')
 page=con.execute("select * from uploads where kind='file' and title='page'").fetchone()
 check(s==200 and page['filename'].endswith('/page.html'),'web pages upload too (httpd only ever sends files as downloads)')

 # ---- Editing: version, tags ------------------------------------------------------
 s,_,_=run('/admin/',{'csrf':csrf,'kind':'file','action':'item_save','id':fid,'title':'BlowfishCMS','collection':'Releases','description':'The first release','version':'1.0.0','tags':'#release','talk_off':'0'},fetch=False)
 row=con.execute('select * from uploads where id=?',(fid,)).fetchone()
 check(s==303 and row['version']=='1.0.0' and con.execute('select tag from item_tags where item=?',(fid,)).fetchone()[0]=='release','version and tags saved')
 s,html,_=run('/admin/?kind=file',fetch=False)
 check('version 1.0.0 · GZ · ' in html and '0 downloads' in html and row['sha256'] in html,'the screen shows each file’s version, size, sha256 and downloads')

 # ---- The file's page -------------------------------------------------------------
 s,html,_=run('/file/%s/'%fid,user='',script_name='/_item')
 check(s==200 and 'href="/download/%s/"'%fid in html and 'download="BlowfishCMS-1.0-final.tar.gz"' in html and row['sha256'] in html and 'version 1.0.0' in html,'each file has a page with its download button, version and sha256')
 check('data-copy-link' in html and 'og:title' in html,'and is shareable')
 check(run('/file/%s/'%('0'*32),user='',script_name='/_item')[0]==404,'a missing file has no page')

 # ---- Downloading -------------------------------------------------------------------
 s,_,hdr=run('/download/%s/'%fid,user='',script_name='/_download')
 check(s in (302,303) and hdr['Location'].endswith('/media/file/%s/BlowfishCMS-1.0-final.tar.gz'%fid),'a download goes on to the file itself')
 check(run('/download/%s/'%('0'*32),user='',script_name='/_download')[0]==404 and run('/download/nope/',user='',script_name='/_download')[0]==404,'unknown downloads are not found')
 (root/'var/db/blowfishcms-comments').mkdir(parents=True)
 for _ in range(3):run('/download/%s/'%fid,user='',script_name='/_download')
 run('/download/%s/'%fid,user='',script_name='/_download',ua='Googlebot/2.1 (+http://www.google.com/bot.html)')
 run('/download/%s/'%fid,user='',script_name='/_download',method='HEAD')
 cdb=sqlite3.connect(root/'var/db/blowfishcms-comments/comments.sqlite')
 check(cdb.execute('select sum(n) from downloads where item=?',(fid,)).fetchone()[0]==3,'downloads are counted, not robots’ or HEAD requests')
 check([r[1] for r in cdb.execute('pragma table_info(downloads)')]==['item','day','n'],'only the file, the day and a count are kept')
 s,html,_=run('/admin/?kind=file',fetch=False);check('3 downloads' in html,'the count shows on the Files screen')
 check('Disallow: /download/' in run('/robots.txt',user='')[1],'robots.txt keeps search engines off download links')

 # ---- Likes, tags and the Download block ---------------------------------------------
 st,body,_=run('/talk/like',{'item':'file:'+fid},user='');check(json.loads(body)['count']==1,'a file can be liked')
 check('BlowfishCMS' in run('/tags/release/',user='',script_name='/_item')[1],'files show on tag pages')
 s,_,hdr=run('/admin/',{'csrf':csrf,'kind':'pages','action':'page_create','label':'Downloads','slug':''},fetch=False)
 for _ in range(2):run('/admin/',{'csrf':csrf,'kind':'page','page':'downloads','action':'block_add','type':'download','width':'full'},fetch=False)
 run('/admin/',{'csrf':csrf,'kind':'pages','action':'nav_toggle','page':'downloads'},fetch=False)
 one,many=[r[0] for r in con.execute("select id from page_blocks where page='downloads' and type='download' order by rowid")]
 con.execute("update page_blocks set data=json_set(data,'$.file',?) where id=?",(fid,one))
 con.execute("update page_blocks set data=json_set(data,'$.tag','release') where id=?",(many,));con.commit()
 html=run('/downloads/',user='',script_name='/_page')[1]
 check(html.count('href="/download/%s/"'%fid)==2 and 'passwd' not in html,'the Download block shows one file, or files with a tag')
 con.execute("update page_blocks set data=json_set(data,'$.tag','') where id=?",(many,));con.commit()
 html=run('/downloads/',user='',script_name='/_page')[1]
 check(all('download="%s"'%n in html for n in ('BlowfishCMS-1.0-final.tar.gz','passwd','page.html')),'or every file')
 check('♥ 1' in html,'with each file’s likes')

 # ---- Bulk and delete --------------------------------------------------------------------
 s,_,_=run('/admin/',{'csrf':csrf,'kind':'file','action':'bulk','op':'delete','ids':[evil['id'],page['id']]},fetch=False)
 check(not (files_dir/evil['id']).exists() and not (files_dir/page['id']).exists() and con.execute("select count(*) from uploads where kind='file'").fetchone()[0]==1,'deleting files removes them and their folders')
 run('/admin/',{'csrf':csrf,'kind':'file','action':'delete','id':fid},fetch=False)
 check(not (files_dir/fid).exists() and con.execute('select count(*) from item_tags where item=?',(fid,)).fetchone()[0]==0,'and their tags')
print(json.dumps({'checks':len(checks)}))