repository

BlowfishCMS

A small content management system for OpenBSD

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

122 lines · 11.2 KB · download this file

#!/usr/bin/env python3
"""Search and sharing on a fresh install: robots.txt, the tags in <head>
(robots, Open Graph, structured data, verification), the share picture,
the sitemap and redirects. Uses a temporary copy of the catalogue; never
touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets
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-seo-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')
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
 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,user='',cookie='',fetch=False,files=None,page_route=False):
  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():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\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':'/_page' if page_route else url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
     'CONTENT_TYPE':ctype,'CONTENT_LENGTH':str(len(body)),'REMOTE_USER':user,'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
 def ld(html):return [json.loads(x) for x in re.findall(r'<script type="application/ld\+json">(.*?)</script>',html,re.S)]
 status,_,hdr=run('/admin/',user='alice');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);cookie='bf_csrf='+csrf
 adm=lambda fields,**o:run('/admin/',{'csrf':csrf,'kind':'search',**fields},user='alice',cookie=cookie,**o)
 search={'action':'search_save','search_visible':'1','entity_type':'person','language':'en','google_verification':'','bing_verification':''}

 # ---- robots.txt and the sitemap -------------------------------------------------
 status,txt,hdr=run('/robots.txt')
 check(status==200 and hdr['Content-Type'].startswith('text/plain') and 'Disallow: /admin' in txt and 'Sitemap: https://example.org/sitemap.xml' in txt and 'Disallow: /\n' not in txt,'robots.txt allows the site and names the sitemap')
 sitemap=run('/sitemap.xml')[1]
 check('<loc>https://example.org/</loc><lastmod>' in sitemap and '/contact/</loc>' in sitemap,'sitemap lists the shown pages with dates')

 # ---- Tags on the homepage --------------------------------------------------------
 sql("insert into site_settings(key,value) values ('site_title','Harbour Notes'),('author','Alice Smith'),('description','Secure comms.') on conflict(key) do update set value=excluded.value")
 html=run('/')[1]
 check('<html lang="en"' in html and 'name="robots"' not in html,'homepage is listable, in English')
 check('<meta property="og:type" content="website">' in html and '<meta property="og:url" content="https://example.org/">' in html and '<meta property="og:description" content="Secure comms.">' in html and 'twitter:card" content="summary"' in html,'every page has Open Graph tags')
 site=[x for x in ld(html) if x['@type']=='WebSite']
 check(site and site[0]['name']=='Harbour Notes' and site[0]['url']=='https://example.org/' and site[0]['publisher']=={'@type':'Person','name':'Alice Smith','url':'https://example.org/'},'homepage describes the site and its owner as structured data')
 check('og:type' in run('/contact/')[1] and not ld(run('/contact/')[1]),'other pages get Open Graph tags but no site data')

 # ---- The settings screen ---------------------------------------------------------
 status,html,_=run('/admin/?kind=search',user='alice',cookie=cookie)
 check(status==200 and 'href="/admin/?kind=search" aria-current="page"' in html and 'class="seo-table"' in html and 'class="is-warn">short' in html,'search & sharing opens, with a check of every page')
 meta='<meta name="google-site-verification" content="AbC_123-xyz987" />'
 status,body,_=adm({**search,'entity_type':'organization','language':'pt-BR','google_verification':meta,'bing_verification':'0123456789ABCDEF0123456789ABCDEF'},fetch=True)
 check(status==200 and json.loads(body)['ok'],'search settings save in the background')
 html=run('/')[1]
 check('<meta name="google-site-verification" content="AbC_123-xyz987">' in html and '<meta name="msvalidate.01" content="0123456789ABCDEF0123456789ABCDEF">' in html,'verification codes on the homepage (a pasted tag is reduced to its code)')
 check('google-site-verification' not in run('/contact/')[1],'verification only on the homepage')
 site=[x for x in ld(html) if x['@type']=='WebSite'][0]
 check('<html lang="pt-BR"' in html and 'og:locale" content="pt_BR"' in html and site['publisher']['@type']=='Organization' and site['inLanguage']=='pt-BR','language and owner type follow the settings')
 for bad,why in [({'google_verification':'"><script>'},'verification code with markup'),({'language':'english!'},'bad language'),({'entity_type':'robot'},'bad owner type')]:
  status,body,_=adm({**search,**bad},fetch=True)
  check(status==400 and not json.loads(body)['ok'],'refused: '+why)
 adm({**search,'search_visible':'0'},fetch=True)
 check('<meta name="robots" content="noindex">' in run('/')[1] and 'Disallow: /\n' in run('/robots.txt')[1],'hiding the site asks search engines to stay away')
 adm(search,fetch=True)
 check('name="robots"' not in run('/')[1],'showing the site again')

 # ---- One page hidden from search engines --------------------------------------------
 sql("update pages set noindex=1 where slug='contact'")
 check('<meta name="robots" content="noindex">' in run('/contact/')[1] and '/contact/</loc>' not in run('/sitemap.xml')[1] and 'name="robots"' not in run('/')[1],'a hidden page is marked noindex and left out of the sitemap')
 sql("update pages set noindex=0 where slug='contact'")

 # ---- Articles ----------------------------------------------------------------------
 pid='a'*32
 sql("insert into posts(id,title,body,published_at,created_at,updated_at) values (?,?,?,?,?,?)",(pid,'Hello </script> world','First paragraph of the post.','2026-11-01T10:00:00Z','2026-11-01T10:00:00Z','2026-11-02T10:00:00Z'))
 html=run('/blog/?post='+pid,page_route=False)[1]
 art=[x for x in ld(html) if x['@type']=='BlogPosting']
 check(art and art[0]['headline']=='Hello </script> world' and art[0]['datePublished']=='2026-11-01T10:00:00Z' and art[0]['dateModified']=='2026-11-02T10:00:00Z' and art[0]['author']['name']=='Alice Smith','articles carry BlogPosting data')
 check('</script> world' not in re.sub(r'<title>.*?</title>|<h1>.*?</h1>','',html).split('application/ld+json')[1].split('</script>')[0],'structured data can\'t close its script element')
 check('<meta property="og:type" content="article">' in html and '<meta property="og:title" content="Hello &lt;/script&gt; world">' in html and 'article:published_time' in html,'articles are shared as articles, titled without the site name')

 # ---- Share picture ---------------------------------------------------------------
 png=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->new(1600,1600,1);$i->filledRectangle(0,0,1599,1599,$i->colorAllocate(20,90,160));binmode STDOUT;print $i->png'],capture_output=True,check=True).stdout
 status,_,_=adm({'action':'share_upload','kind':'settings'},files=[('share_image','s.png',png)])
 sid=sql("select value from site_settings where key='share_image'")[0][0]
 f=media/'site'/f'share-{sid}.jpg'
 dims=subprocess.run(['perl','-MGD','-e','print join "x",GD::Image->new($ARGV[0])->getBounds',str(f)],capture_output=True,text=True).stdout
 check(status==303 and dims=='1200x630','share picture cropped to 1200 × 630')
 html=run('/contact/')[1]
 check(f'<meta property="og:image" content="https://example.org/media/site/share-{sid}.jpg">' in html and 'summary_large_image' in html,'pages share with the picture')
 small=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->new(300,300,1);binmode STDOUT;print $i->png'],capture_output=True,check=True).stdout
 check(adm({'action':'share_upload','kind':'settings'},files=[('share_image','s.png',small)])[0]==200 and f.exists(),'a picture too small is refused; the old one stays')
 adm({'action':'share_reset','kind':'settings'})
 check(not f.exists() and 'og:image' not in run('/contact/')[1],'share picture removed')

 # ---- Redirects ----------------------------------------------------------------------
 status,_,hdr=adm({'action':'redirect_add','from':'old-news','to':'/blog/'})
 check(status==303,'redirect added (the address is tidied into /old-news/)')
 status,_,hdr=run('/old-news/',page_route=True)
 check(status==301 and hdr['Location']=='https://example.org/blog/','old address answers with a permanent redirect')
 adm({'action':'redirect_add','from':'/older/','to':'/old-news/'})
 adm({'action':'redirect_add','from':'/old-news/','to':'https://elsewhere.example/news'})
 check(run('/older/',page_route=True)[2]['Location']=='https://elsewhere.example/news' and run('/old-news/',page_route=True)[2]['Location']=='https://elsewhere.example/news','chains are collapsed; full addresses work')
 for bad,why in [({'from':'/contact/','to':'/blog/'},'a page uses that address'),({'from':'/a/b/','to':'/blog/'},'not a page address'),({'from':'/x/','to':'javascript:alert(1)'},'unsafe target'),({'from':'/x/','to':'//evil.example/'},'protocol-relative target'),({'from':'/x/','to':'/x/'},'redirect to itself')]:
  check(adm({'action':'redirect_add',**bad})[0]==200 and not sql("select 1 from redirects where from_path=?",(bad['from'],)),'redirect refused: '+why)
 adm({'action':'redirect_delete','from':'/older/'})
 check(run('/older/',page_route=True)[0]==404,'redirect removed')
 check(run('/no-such-page/',page_route=True)[0]==404,'unknown addresses still 404')

 print(json.dumps({'checks':len(checks)}))