repository

BlowfishCMS

A small content management system for OpenBSD

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

174 lines · 14.5 KB · download this file

#!/usr/bin/env python3
"""The Mail screen (/admin/mail/, run by the contact service) and contact form
delivery, against a local stand-in for the Postmark API. No real email is
sent. Uses a temporary copy of the catalogue; never touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,threading,http.server,stat
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)

# ---- A stand-in for Postmark --------------------------------------------------
GOOD='aaaa1111-bbbb-2222-cccc-3333dddd4444'
sent=[]
class Postmark(http.server.BaseHTTPRequestHandler):
 def log_message(self,*a):pass
 def reply(self,status,body):
  data=json.dumps(body).encode();self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
 def do_GET(self):
  if self.path=='/server' and self.headers.get('X-Postmark-Server-Token')==GOOD:return self.reply(200,{'Name':'Harbour Notes server','ID':1})
  self.reply(401,{'ErrorCode':10,'Message':'Bad or missing Server API token.'})
 def do_POST(self):
  body=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
  if self.headers.get('X-Postmark-Server-Token')!=GOOD:return self.reply(401,{'ErrorCode':10,'Message':'Bad token'})
  sent.append(body)
  if 'pending' in body['To']:return self.reply(422,{'ErrorCode':412,'Message':'Pending approval'})
  self.reply(200,{'ErrorCode':0,'MessageID':'msg-%d'%len(sent),'Message':'OK'})
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Postmark)
threading.Thread(target=server.serve_forever,daemon=True).start()

with tempfile.TemporaryDirectory(prefix='blowfish-mail-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\nmail_from = site@example.org\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)
 contact=root/'var/db/bf-contact';contact.mkdir(parents=True,mode=0o700)
 secrets_dir=root/'etc/bf';secrets_dir.mkdir(parents=True,mode=0o700)
 env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_POSTMARK_API':'http://127.0.0.1:%d'%server.server_port}
 env.pop('BLOWFISH_PAGES_SEED',None)
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
 def sql(q,args=()):
  with signin.connect(data/'catalog.sqlite') as c:return c.execute(q,args).fetchall()
 def run(path,fields=None,user='',cookie=''):
  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':user,'HTTP_ORIGIN':'https://example.org','HTTP_COOKIE':cookie,'REMOTE_ADDR':'192.0.2.%d'%(len(sent)+10)}
  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 notice(hdr):return urllib.parse.unquote(hdr.get('Location','').split('notice=',1)[-1])

 # ---- The screen --------------------------------------------------------------
 check('href="/admin/mail/"' in run('/admin/?kind=settings',user='alice')[1],'Settings has a Mail tab')
 check(run('/admin/mail/',user='mallory')[0] in (303,401,403),'only the admin account gets the mail screen')
 status,html,hdr=run('/admin/mail/',user='alice')
 check(status==200 and 'aria-current="page">Mail' in html and 'not set' in html and 'bf_mail_csrf=' in hdr.get('Set-Cookie','') and 'Path=/admin/mail/' in hdr['Set-Cookie'],'mail screen opens with its own form key; no token yet')
 check('"My site" <site@example.org>' in html and 'pm-bounces.example.org' in html,'the sender defaults to the install\'s address and the site name')
 check([t for t in __import__('re').findall(r'window__glyph" aria-hidden="true"></span>([^<]+)</div>',html)]==['postmark','messages','recent deliveries'] and '<details class="box-part mail-setup" open>' in html,'three boxes: Postmark (setup steps open until there’s a token), messages, recent deliveries')
 csrf=re.match(r'bf_mail_csrf=([^;]+)',hdr['Set-Cookie']).group(1);cookie='bf_mail_csrf='+csrf
 post=lambda fields:run('/admin/mail/',{'csrf':csrf,'kind':'mail',**fields},user='alice',cookie=cookie)
 check('expired' in run('/admin/mail/',{'kind':'mail','action':'check'},user='alice',cookie=cookie)[1],'forms without the key are refused')
 check(run('/admin/mail/',{'csrf':csrf,'kind':'mail','action':'check'},user='alice',cookie='bf_csrf='+csrf)[1].count('expired')>0,'the admin\'s own key doesn\'t work here')

 # ---- The token ------------------------------------------------------------------
 tokfile=secrets_dir/'postmark.token'
 status,html,_=post({'action':'token_save','token':'short'})
 check(status==200 and 'doesn’t look like a Postmark server token' in html and not tokfile.exists(),'a malformed token is refused')
 status,html,_=post({'action':'token_save','token':'ffff0000-ffff-0000-ffff-0000ffff0000'})
 check(status==200 and 'Postmark refused the server token' in html and not tokfile.exists(),'a token Postmark refuses is not saved, with the reason')
 status,_,hdr=post({'action':'token_save','token':' '+GOOD+'\n'})
 check(status==303 and 'Postmark server: Harbour Notes server' in notice(hdr) and tokfile.read_text()==GOOD+'\n' and stat.S_IMODE(tokfile.stat().st_mode)==0o400,'a good token is checked with Postmark and saved readable only by the contact service')
 html=run('/admin/mail/',user='alice',cookie=cookie)[1]
 check(GOOD not in html and 'saved (Postmark server: Harbour Notes server)' in html,'the token is never shown again')

 # ---- The sender ---------------------------------------------------------------
 for bad in [{'from_address':'not-an-address','from_name':'X'},{'from_address':'a@example.org','from_name':'Evil" <x@y>'}]:
  check(post({'action':'sender_save',**bad})[0]==200,'sender refused: '+json.dumps(bad))
 status,_,hdr=post({'action':'sender_save','from_address':'Hello@Example.org','from_name':'Harbour Notes'})
 cfg=json.loads((contact/'mail.json').read_text())
 check(status==303 and cfg['from_address']=='hello@example.org' and cfg['from_name']=='Harbour Notes' and stat.S_IMODE((contact/'mail.json').stat().st_mode)==0o600,'sender saved in the contact folder')

 # ---- Test messages --------------------------------------------------------------
 status,html,_=post({'action':'test_send'})
 check(status==200 and 'Set the receiving address first' in html and not sent,'no test without a receiving address')
 check('Receiving address: enter an address' in post({'action':'receiving_save','to':'nope'})[1],'the receiving address is checked')
 check('Alerts address: enter an address' in post({'action':'alerts_save','alerts':'nope'})[1],'the alerts address is checked')
 status,_,hdr=post({'action':'alerts_save','alerts':'Alerts@Example.org'})
 check(status==303 and json.loads((contact/'mail.json').read_text())['alerts']=='alerts@example.org' and 'value="alerts@example.org"' in run('/admin/mail/',user='alice',cookie=cookie)[1],'update alerts go to the address saved under messages')
 post({'action':'alerts_save','alerts':''})
 check(json.loads((contact/'mail.json').read_text())['alerts']=='','and it can be emptied: no alerts')
 status,_,hdr=post({'action':'receiving_save','to':'Me@Example.org'})
 check(status==303 and json.loads((contact/'mail.json').read_text())['to']=='me@example.org','the receiving address is saved on the Mail screen, in the contact folder')
 check('me@example.org' not in run('/contact/')[1],'visitors never see the receiving address')
 status,_,hdr=post({'action':'test_send'})
 check(status==303 and 'accepted the test message for me@example.org' in notice(hdr) and sent[-1]['To']=='me@example.org' and sent[-1]['From']=='"Harbour Notes" <hello@example.org>' and sent[-1]['MessageStream']=='outbound','a test message goes through Postmark from the sender')
 post({'action':'receiving_save','to':'pending@other.example'})
 status,html,_=post({'action':'test_send'})
 check(status==200 and 'pending approval' in html,'a Postmark error is explained')
 html=run('/admin/mail/',user='alice',cookie=cookie)[1]
 check('Test message accepted msg-1' in html and 'errorCode=412' in html,'recent deliveries are listed')
 post({'action':'receiving_save','to':'me@example.org'})

 # ---- The contact form uses the same set-up ---------------------------------------------
 before=len(sent)
 status,_,hdr=run('/contact/send',{'form_name':'contact','name':'Visitor','email':'visitor@example.net','subject':'Hi','message':'Hello there'})
 m=sent[-1] if len(sent)>before else {}
 check(status==303 and hdr['Location']=='/contact/?sent=1' and m.get('From')=='"Harbour Notes" <hello@example.org>' and m.get('ReplyTo')=='visitor@example.net' and m.get('To')=='me@example.org' and 'Hello there' in m.get('TextBody',''),'contact form messages go from the sender, reply to the visitor')

 # ---- Check and removal ---------------------------------------------------------
 status,_,hdr=post({'action':'check'})
 check(status==303 and 'accepts the token' in notice(hdr),'check again asks Postmark')
 status,_,hdr=post({'action':'token_remove'})
 check(status==303 and not tokfile.exists(),'token removed')
 status,_,hdr=run('/contact/send',{'form_name':'contact','name':'Visitor','email':'visitor@example.net','message':'Hello again'})
 check(hdr['Location']=='/contact/?sent=0','without a token the form reports failure instead of pretending')
 post({'action':'token_save','token':GOOD})
 results=[post({'action':'test_send'})[1] for i in range(9)]
 check(sum('ten test messages this hour' in r for r in results)==1 and 'ten test messages this hour' in results[-1],'at most ten test messages an hour')
 # Looking up a name that resolves (the Return-Path check) gives its addresses.
 out=subprocess.run(['perl','-I'+str(pathlib.Path(script).parent.parent/'lib'),'-MBlowfishCMS','-e','print join(",",BlowfishCMS::host_addresses("localhost")),"|",join(",",BlowfishCMS::host_addresses("no-such-host.invalid"))'],env=env,capture_output=True,text=True)
 check(out.returncode==0 and out.stdout.split('|')[0].startswith('127.') and out.stdout.endswith('|'),'DNS lookups for the Return-Path check work: '+out.stdout+out.stderr[:200])
 # ---- Mail from add-ons: queued, relayed, sent ------------------------------------
 lib=str(pathlib.Path(script).parent.parent/'lib')
 def queue(source,**m):
  code='BlowfishCMS::load_instance() if defined &BlowfishCMS::load_instance;print BlowfishCMS::mail_queue(@ARGV)'
  args=[source]+[x for k,v in m.items() for x in (k,v)]
  return subprocess.run(['perl','-I'+lib,'-MBlowfishCMS','-e',code,*args],env=env,capture_output=True,text=True)
 (root/'var/db/blowfishcms-addons/store').mkdir(parents=True)
 r=queue('store',to='owner',subject='New order 1001',text='Two mugs.',tag='order',from_name='Example Shop')
 out=root/'var/db/blowfishcms-addons/store/outbox'
 check(r.returncode==0 and len(list(out.glob('*.json')))==1,'an add-on queues mail in its own outbox: '+r.stderr[:200])
 check(oct((out/list(out.glob('*.json'))[0].name).stat().st_mode & 0o777)=='0o600' and not list(out.glob('.*')),'privately, with nothing half-written left')
 r=queue('store',to='buyer@example.net',subject='Your order',text='Thank you.',reply_to='shop@example.org')
 check(r.returncode==0,'(a second message, to the buyer)')
 r=queue('store',to='not an address',subject='x',text='y')
 check(r.returncode!=0 and 'someone to send it to' in r.stderr,'an address that isn’t one is refused when queuing')
 r=queue('core',to='owner',subject='From the admin',text='Hi.')
 check(r.returncode==0 and len(list((data/'outbox').glob('*.json')))==1,'the admin service queues in its own outbox when an add-on’s isn’t writable')
 # What blowfishctl's relay does: move them into the contact folder's queue.
 q=contact/'mailq';q.mkdir(mode=0o700)
 for box in [out,data/'outbox']:
  for f in box.glob('*.json'):f.rename(q/(box.parent.name+'-'+f.name))
 post({'action':'alerts_save','alerts':''})
 before=len(sent)
 snd=subprocess.run(['perl',script,'--mail-send'],env=env,capture_output=True,text=True)
 got=sent[before:]
 tos=sorted(m['To'] for m in got)
 check(snd.returncode==0 and 'buyer@example.net' in tos,'the contact form’s account sends the queue: '+snd.stdout+snd.stderr[:200])
 owner_to=json.loads((contact/'mail.json').read_text()).get('to','')
 check(tos.count(owner_to)==2 if owner_to else True,'mail “to owner” goes to the receiving address while no alerts address is set')
 order=[m for m in got if m['Subject']=='New order 1001'][0]
 check(order['From'].startswith('"Example Shop" <') and order['Tag']=='order' and order['TextBody']=='Two mugs.' and order['MessageStream']=='outbound','with its sender name, tag and text, from the site’s address')
 buyer=[m for m in got if m['To']=='buyer@example.net'][0]
 check(buyer['ReplyTo']=='shop@example.org','and its reply address')
 check(not list(q.glob('*.json')) and 'Queued message from store accepted' in (contact/'contact.log').read_text(),'sent messages leave the queue and are logged')
 # With an alerts address, "owner" means it.
 post({'action':'alerts_save','alerts':'alerts@example.org'})
 queue('store',to='owner',subject='Another',text='x')
 for f in out.glob('*.json'):f.rename(q/('store-'+f.name))
 before=len(sent);subprocess.run(['perl',script,'--mail-send'],env=env,capture_output=True)
 check([m['To'] for m in sent[before:]]==['alerts@example.org'],'with an update alerts address, mail to the owner goes there')
 # Without a token, the queue waits.
 post({'action':'token_remove'})
 queue('store',to='owner',subject='Waiting',text='x')
 for f in out.glob('*.json'):f.rename(q/('store-'+f.name))
 snd=subprocess.run(['perl',script,'--mail-send'],env=env,capture_output=True,text=True)
 check(snd.returncode==3 and len(list(q.glob('*.json')))==1,'without a token the queue waits')
 print(json.dumps({'checks':len(checks)}))
server.shutdown()