repository

BlowfishCMS

A small content management system for OpenBSD

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

179 lines · 17.6 KB · download this file

#!/usr/bin/env python3
"""Analytics: public pages count their views through /stats/hit (no cookies;
robots, the admin's addresses, unknown pages and other sites aren't counted);
visitors are counted once a day without keeping their address; the numbers
are the comments service's alone; the Analytics screen is for owners; it can
be turned off, which takes the script off public pages. Uses a fresh
catalogue; never touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,re,urllib.parse,secrets,datetime,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)
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
CHROME='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
IPHONE='Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'
FIREFOX='Mozilla/5.0 (X11; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0'
BOT='Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
with tempfile.TemporaryDirectory(prefix='blowfish-analytics-test-') as tmp:
 root=pathlib.Path(tmp)
 conf=root/'etc/blowfishcms.conf';conf.parent.mkdir(parents=True)
 conf.write_text('domain = stats.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)
 cdata=root/'var/db/bf-comments';(root/'var/db/bf-contact').mkdir(parents=True);cdata.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';stats=cdata/'analytics/analytics.sqlite'
 def sql(q,a=(),file=db):
  c=sqlite3.connect(file)
  try:
   with c:return c.execute(q,a).fetchall()
  finally:c.close()
 def run(path,fields=None,cookie='',ua=CHROME,ip='192.0.2.7',origin='https://stats.example.org'):
  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':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':origin or '','HTTP_COOKIE':cookie,'REMOTE_ADDR':ip,'HTTP_USER_AGENT':ua}
  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):
  status,_,hdr=run('/admin/',{'csrf':csrf,'kind':'login','user':user,'password':password,'next':'/admin/'},cookie='bf_csrf='+csrf)
  s=cookie_of(hdr,'bf_session');return f'bf_csrf={csrf}; bf_session={s}' if status==303 and s else None
 alice=sign_in('alice','alice password one')
 run('/admin/',{'csrf':csrf,'kind':'users','action':'user_add','name':'bob','email':'','role':'editor','password':'bob password one','password2':'bob password one'},cookie=alice)
 bob=sign_in('bob','bob password one')
 check(alice and bob,'an owner and an editor sign in')
 other=next(p for (p,) in sql("select path from pages where path<>'/' order by path") if run(p)[0]==200)

 # ---- Public pages ----------------------------------------------------------------------
 status,home,hdr=run('/')
 check(status==200 and '<script defer src="/js/stats.js?v=2"></script>' in home and 'Set-Cookie' not in hdr,'public pages load the small counting script, and set no cookie')
 check('Disallow: /stats/' in run('/robots.txt')[1],'search engines are asked to leave /stats/ alone')
 def hit(path,ua=CHROME,ref='',width='1440',ip='192.0.2.10',origin='https://stats.example.org',tag=''):
  return run('/stats/hit',{'p':path,'r':ref,'w':width,'t':tag},ua=ua,ip=ip,origin=origin)
 status,body,hdr=hit('/',ref='https://www.search.example/?q=fish')
 check(status==204 and body=='' and 'Set-Cookie' not in hdr,'a view is counted, answering nothing')
 hit('/',ref='https://stats.example.org/somewhere/')
 hit(other,ua=IPHONE,width='390',ip='192.0.2.11',ref='https://social.example/post/1')
 hit('/',ua=FIREFOX,ip='192.0.2.12')
 hit('/',ua=BOT,ip='192.0.2.13')
 hit('/no-such-page/',ip='192.0.2.14')
 hit('/admin/',ip='192.0.2.15')
 hit('/stats/hit',ip='192.0.2.16')
 hit('/',ip='192.0.2.17',origin='https://evil.example')
 check(run('/stats/hit')[0]==204,'a GET counts nothing')
 today=datetime.date.today().isoformat()
 check(sql('select day,views,visitors from daily',file=stats)==[(today,4,3)],'four views from three visitors: robots, unknown pages, the admin and other sites aren’t counted')
 check(dict(sql('select path,views from pages',file=stats))=={'/':3,other:1},'views per page')
 check(dict(sql('select source,visits from sources',file=stats))=={'search.example':1,'social.example':1,'':1},'where visits came from, counted once each when they arrive (the site’s own pages aren’t a source, and don’t count as “not known”)')
 agents={(k,n):v for k,n,v in sql('select kind,name,views from agents',file=stats)}
 check(agents[('browser','Chrome')]==2 and agents[('browser','Safari')]==1 and agents[('browser','Firefox')]==1 and agents[('system','iOS')]==1 and agents[('device','Phone')]==1 and agents[('device','Computer')]==3,'browsers, systems and devices')
 raw=b''.join(p.read_bytes() for p in (cdata/'analytics').glob('analytics.sqlite*'))
 check(b'192.0.2' not in raw and b'Mozilla' not in raw,'no address or browser string is kept')
 check(oct((cdata/'analytics').stat().st_mode&0o777)=='0o700','the numbers are the comments service’s alone')
 salts=list((cdata/'analytics').glob('salt-*'))
 check([p.name for p in salts]==[f'salt-{today}'] and oct(salts[0].stat().st_mode&0o777)=='0o600','today’s salt is private')
 sql("insert into seen (day,hash,hits) values ('2020-01-01','abc',1)",file=stats)
 (cdata/f'analytics/salt-{today}').unlink();(cdata/'analytics/salt-2020-01-01').write_text('old')
 hit('/')
 check(sql('select count(*) from seen where day<?',(today,),file=stats)==[(0,)] and not (cdata/'analytics/salt-2020-01-01').exists(),'yesterday’s visitors and salt are deleted with the new day')

 # ---- The screen ------------------------------------------------------------------------
 check(run('/admin/analytics/')[0] in (302,303,401,403),'the Analytics screen needs a signed-in admin')
 status,html,_=run('/admin/analytics/',cookie=bob)
 check(status==403 or 'owner' in html.lower() and 'analytics-chart' not in html,'editors can’t open it')
 check('/admin/analytics/' not in run('/admin/',cookie=bob)[1],'editors don’t see it in the sidebar')
 check(run('/admin/analytics',cookie=alice)[0]==303,'/admin/analytics goes to /admin/analytics/')
 status,html,hdr=run('/admin/analytics/',cookie=alice)
 check(status==200 and 'Page views</span><strong>5</strong>' in html and '<svg class="analytics-chart"' in html,'owners see views, visitors and a chart per day')
 check('<span class="an-name">/</span><span class="an-n">4</span>' in html and '<span class="an-name">search.example</span>' in html and '<span class="an-name">Chrome</span>' in html and '<span class="an-name">not known</span>' in html and 'direct, or not said' not in html,'and the top pages, sources (by visit), browsers and devices')
 check('data-analytics-self' in html and 'href="/admin/analytics/" aria-current="page"' in html,'it’s in the sidebar, and lets the owner count their own browser or not')
 check('aria-current="true">7 days</a>' in run('/admin/analytics/?days=7',cookie=alice)[1],'the period can be 7, 30, 90 or 365 days')
 check(html.count('class="analytics-grid"')==1 and '<details class="an-fold" id="more"><summary>Make a tagged link to share</summary>' in html and '<summary>About these numbers</summary>' in html,'the screen is compact: four lists two by two, the link maker and the notes folded away')

 # ---- Off and on -----------------------------------------------------------------------------
 token=cookie_of(hdr,'bf_analytics_csrf');ck=alice+'; bf_analytics_csrf='+token
 check(run('/admin/analytics/',{'csrf':'wrong','action':'analytics_off'},cookie=ck)[0]==403 and not (cdata/'analytics-off').exists(),'turning it off needs the form’s token')
 status,_,hdr=run('/admin/analytics/',{'csrf':token,'action':'analytics_off'},cookie=ck)
 check(status==303 and (cdata/'analytics-off').exists(),'an owner turns Analytics off')
 check('/js/stats.js' not in run('/')[1],'then public pages don’t load the script')
 before=sql('select views from daily',file=stats)[0][0];hit('/',ip='192.0.2.40')
 check(sql('select views from daily',file=stats)[0][0]==before,'and nothing is counted')
 check('Analytics is off' in run('/admin/analytics/',cookie=alice)[1],'the screen says it’s off')
 run('/admin/analytics/',{'csrf':token,'action':'analytics_on'},cookie=ck)
 check(not (cdata/'analytics-off').exists() and '/js/stats.js' in run('/')[1],'and turns it back on')

 # ---- Visits and where they came from (0.39.5) -------------------------------------------------
 def visit_of(ip):
  # The newest visit from a test address, found by its first page's time (the visit keeps no address).
  return sql('select id,source,via,landing,views from visits order by id desc limit 1',file=stats)[0]
 hit('/',ip='192.0.2.50',ref='https://www.linkedin.com/');hit(other,ip='192.0.2.50',ref='https://stats.example.org/')
 v=visit_of('192.0.2.50')
 check(v[1:]==('LinkedIn','linkedin.com','/',2) and [p for (p,) in sql('select path from visit_views where visit=? order by at,rowid',(v[0],),file=stats)]==['/',other],'a visit keeps its pages in order, and where it came from, named')
 for ref,want in [('android-app://com.linkedin.android/',('LinkedIn','the LinkedIn app')),('android-app://com.example.reader/',('com.example.reader','an Android app')),
                  ('https://m.youtube.com/watch?v=x',('YouTube','m.youtube.com')),('https://l.facebook.com/l.php',('Facebook','l.facebook.com')),('https://www.google.co.uk/',('Google','google.co.uk')),
                  ('https://mail.google.com/mail/u/0/',('Gmail','mail.google.com')),('https://steamcommunity.com/linkfilter/?u=x',('Steam','steamcommunity.com')),('https://news.example/a',('news.example','news.example'))]:
  hit('/',ip='192.0.2.51',ref=ref)
  check(visit_of('192.0.2.51')[1:3]==want,f'{ref} is counted as {want[0]}')
 hit('/',ip='192.0.2.52',tag='Steam');check(visit_of('')[1:3]==('Steam','link tagged ref=steam'),'a tagged link (?ref=steam) names where it was posted, with no referrer at all')
 hit('/',ip='192.0.2.53',tag='newsletter',ref='https://www.linkedin.com/');check(visit_of('')[1:3]==('Email','link tagged ref=newsletter'),'a tag wins over the referrer, and known words are grouped (newsletter is Email)')
 hit('/',ip='192.0.2.54',tag='My Podcast!');check(visit_of('')[1:3]==('my-podcast','link tagged ref=my-podcast'),'any other word is kept as it is, cleaned')
 # A new visit after half an hour, or when the same visitor arrives again from elsewhere.
 n=sql('select count(*) from visits',file=stats)[0][0]
 sql('update current set last=last-1900',file=stats);hit(other,ip='192.0.2.50',ref='https://stats.example.org/')
 check(sql('select count(*) from visits',file=stats)[0][0]==n+1 and visit_of('')[1:]==('','',other,1),'half an hour without a page starts a new visit')
 hit('/',ip='192.0.2.50',ref='https://www.youtube.com/');hit(other,ip='192.0.2.50',ref='https://stats.example.org/')
 check(sql('select count(*) from visits',file=stats)[0][0]==n+2 and visit_of('')[1:]==('YouTube','youtube.com','/',2),'arriving again from elsewhere starts a new one; the site’s own links don’t')
 check('hash' not in [c[1] for c in sql('pragma table_info(visits)',file=stats)],'a visit keeps no visitor hash')
 # The screen: each visit, where from, and its pages.
 html=H.unescape(run('/admin/analytics/',cookie=alice)[1])
 check('class="analytics-visits"' in html and re.search(r'analytics-visit__from">LinkedIn <span class="media-label">linkedin.com</span>.*?2 pages.*?<a href="/"',html,re.S) and f'<a href="{other}"' in html,'the screen lists visits: where from, how many pages, and each page')
 check('<span class="an-name">LinkedIn</span>' in html and '<span>visits</span>' in html and 'Tag your links' in html,'and counts visits per source')
 only=H.unescape(run('/admin/analytics/?from=Steam',cookie=alice)[1])
 check(only.count('<li><details>')==2 and 'analytics-visit__from">LinkedIn' not in only,'visits can be shown from one source only')
 made=H.unescape(run('/admin/analytics/?lp=%2F&tag=LinkedIn',cookie=alice)[1])
 check('value="https://stats.example.org/?ref=linkedin"' in made and 'counted as “LinkedIn”' in made,'it makes a tagged link to share')
 check('value="https://stats.example.org/?ref=' not in H.unescape(run('/admin/analytics/?lp=/nowhere/&tag=x',cookie=alice)[1]),'only for a page of the site')
 # Visits are kept 90 days.
 sql("insert into visits (day,started,last,source,via,landing,views,code,country,region,city,browser,system,device) values ('2020-01-01',0,0,'','','/',1,'','','','','','','')",file=stats)
 old=sql("select id from visits where day='2020-01-01'",file=stats)[0][0];sql('insert into visit_views (visit,at,path) values (?,0,?)',(old,'/'),file=stats)
 (cdata/f'analytics/salt-{today}').unlink();hit('/',ip='192.0.2.55')
 check(sql("select count(*) from visits where day='2020-01-01'",file=stats)==[(0,)] and sql('select count(*) from visit_views where visit=?',(old,),file=stats)==[(0,)],'visits older than 90 days go, with their pages')
 # ---- Places (0.28) -----------------------------------------------------------------------
 html=H.unescape(run('/admin/analytics/',cookie=alice)[1])
 check('blowfishctl places' in html and sql("select count(*) from places where code<>''",file=stats)==[(0,)] and sql("select sum(views) from places where code=''",file=stats)[0][0]>0,'without the city database, views are counted with no place, and the screen says how to get it')
 sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent));import mmdb_fixture
 mmdb_fixture.write(str(cdata/'analytics/places.mmdb'),mmdb_fixture.SAMPLE)
 out=subprocess.run(['perl',script,'--places-check',str(cdata/'analytics/places.mmdb')],env=env,capture_output=True,text=True)
 check(out.returncode==0 and out.stdout.startswith('ok: DBIP-City-Lite'),'site.pl --places-check accepts a city database (blowfishctl places checks with it)')
 bad=cdata/'analytics/not.mmdb';bad.write_bytes(b'not a database');out=subprocess.run(['perl',script,'--places-check',str(bad)],env=env,capture_output=True,text=True);bad.unlink()
 check(out.returncode!=0,'and refuses anything else')
 sql("delete from places",file=stats)
 for ip,n in [('192.0.2.20',2),('198.51.100.5',1),('203.0.113.200',1),('2001:db8:1::9',1),('::ffff:192.0.2.21',1),('8.8.8.8',1)]:
  for _ in range(n):hit('/',ip=ip)
 rows={(c,r,ci):(v,u) for c,r,ci,v,u in sql('select code,region,city,views,visitors from places',file=stats)}
 check(rows.get(('US','NV','Las Vegas'))==(3,2) and rows.get(('US','NV','Reno'))==(1,1),'each view is counted with its place: city, region (by its short code in the US) and country; visitors once')
 check(rows.get(('FR','',''))==(1,1) and rows.get(('CH','Zurich','Zürich'))==(1,1) and rows.get(('','',''))==(1,1),'a country alone, IPv6 addresses, and places the database doesn’t know')
 raw=b''.join(p.read_bytes() for p in (cdata/'analytics').glob('analytics.sqlite*'))
 check(b'192.0.2' not in raw and b'198.51.100' not in raw and b'2001:db8' not in raw,'only the place is kept, never the address')
 html=run('/admin/analytics/',cookie=alice)[1]
 check('<span class="an-name">Las Vegas, NV, United States</span><span class="an-n">3</span>' in html and '<span class="an-name">Zürich, Zurich, Switzerland</span>' in html and '<span class="an-name">France</span>' in html and '<span class="an-name">unknown</span>' in html,'the screen lists places')
 check('<span class="an-name">United States</span><span class="an-n">4</span>' in html and 'href="https://db-ip.com">IP Geolocation by DB-IP</a>' in html,'and countries, crediting DB-IP as its licence asks')
 # The chart, for days with no views among days with some: no warnings (they filled httpd's error log).
 lib=str(pathlib.Path(__file__).resolve().parents[1]/'lib')
 r=subprocess.run(['perl','-I',lib,'-MBlowfishCMS','-e','print BlowfishCMS::analytics_chart(["2026-11-20","2026-11-21","2026-11-22"],{"2026-11-22"=>[5,2]})'],env=env,capture_output=True,text=True)
 check(r.returncode==0 and r.stderr=='' and r.stdout.count('<rect')==6,'the chart draws days with no views without a warning')
 print(f'{{"checks": {len(checks)}}}')