BS-007 Implement accepted Contact page and independent enquiry service

This commit is contained in:
rob
2026-11-10 19:45:11 +00:00
parent 21d048a1ff
commit 5bfb128e94
46 changed files with 837 additions and 145 deletions
+129
View File
@@ -0,0 +1,129 @@
"""Independent, database-free BortStack enquiry service. No account imports."""
import json
import os
import re
from email.utils import parseaddr
from html import escape
from urllib.request import Request, urlopen
from uuid import UUID
from flask import Flask, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from werkzeug.middleware.proxy_fix import ProxyFix
SERVICES = ('Website Development', 'Custom Software & Web Applications',
'API Development & Integration', 'Managed Hosting & Maintenance')
def valid_email(value):
return (isinstance(value, str) and len(value) <= 254
and re.fullmatch(r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+", value) is not None)
def deliver(payload, key, config):
"""Bounded provider call; only provider acceptance with an ID counts as success."""
req = Request('https://api.resend.com/emails', data=json.dumps(payload).encode(),
headers={'Authorization': f"Bearer {config['RESEND_API_KEY']}",
'Content-Type': 'application/json', 'Idempotency-Key': f'contact/{key}'},
method='POST')
with urlopen(req, timeout=10) as response:
result = json.loads(response.read(16384))
if not isinstance(result, dict) or not isinstance(result.get('id'), str) or not result['id']:
raise ValueError('Provider did not acknowledge acceptance')
def create_app(overrides=None):
app = Flask(__name__)
app.config.update(MAX_CONTENT_LENGTH=32768,
CONTACT_EMAIL=os.environ.get('CONTACT_EMAIL', ''),
EMAIL_FROM=os.environ.get('EMAIL_FROM', ''),
RESEND_API_KEY=os.environ.get('RESEND_API_KEY', ''),
EMAIL_DELIVERY_ENABLED=os.environ.get('EMAIL_DELIVERY_ENABLED', 'false').lower() == 'true',
CONTACT_TRUST_PROXY=os.environ.get('CONTACT_TRUST_PROXY', 'false').lower() == 'true')
if overrides:
app.config.update(overrides)
# Enable only behind a single trusted proxy that overwrites client headers.
if app.config['CONTACT_TRUST_PROXY']:
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
limiter = Limiter(get_remote_address, app=app, storage_uri='memory://')
app.extensions['contact_limiter'] = limiter
def configured():
sender = app.config['EMAIL_FROM']
return bool(app.config['EMAIL_DELIVERY_ENABLED']
and valid_email(app.config['CONTACT_EMAIL'])
and isinstance(sender, str) and '\r' not in sender and '\n' not in sender
and valid_email(parseaddr(sender)[1]) and app.config['RESEND_API_KEY'])
@app.get('/api/health')
@app.get('/api/health/live')
@app.get('/api/health/ready')
def health():
# Process readiness is separate from externally configured mail availability.
return {'status': 'ready'}
@app.get('/api/contact/config')
def contact_config():
email = app.config['CONTACT_EMAIL']
response = app.json.response({'email': email if valid_email(email) else None,
'available': configured()})
response.headers['Cache-Control'] = 'no-store'
return response
@app.errorhandler(413)
def too_large(_error):
return {'message': 'Message is too large.'}, 413
@app.errorhandler(429)
def limited(_error):
return {'message': 'Too many attempts. Please try again later.'}, 429, {'Retry-After': '3600'}
@app.post('/api/contact')
@limiter.limit('5 per hour;20 per day')
def contact():
data = request.get_json(silent=True)
if not isinstance(data, dict):
return {'message': 'Send a valid enquiry.'}, 400
allowed = {'name', 'email', 'service', 'description', 'website'}
if set(data) - allowed or any(not isinstance(v, str) for v in data.values()):
return {'message': 'Send a valid enquiry.'}, 400
if data.get('website', ''):
return {'message': 'Unable to accept this enquiry.'}, 400
values = {k: data.get(k, '').strip() for k in allowed}
errors = {}
if not 1 <= len(values['name']) <= 100 or any(ord(c) < 32 for c in values['name']):
errors['name'] = 'Enter your name (up to 100 characters).'
if not valid_email(values['email']):
errors['email'] = 'Enter a valid email address.'
if values['service'] and values['service'] not in SERVICES:
errors['service'] = 'Choose one of the listed services or leave it blank.'
if not 10 <= len(values['description']) <= 5000 or '\x00' in values['description']:
errors['description'] = 'Describe your project in 10 to 5,000 characters.'
if errors:
return {'message': 'Please check the highlighted fields.', 'errors': errors}, 400
key = request.headers.get('Idempotency-Key', '')
try:
if str(UUID(key)) != key:
raise ValueError()
except (ValueError, AttributeError):
return {'message': 'Refresh the page and try again.'}, 400
if not configured():
return {'message': 'Enquiries are temporarily unavailable. Your message has not been sent.'}, 503
service = values['service'] or 'General enquiry'
text = f"Name: {values['name']}\nEmail: {values['email']}\nService: {service}\n\n{values['description']}"
payload = {'from': app.config['EMAIL_FROM'], 'to': [app.config['CONTACT_EMAIL']],
'reply_to': values['email'], 'subject': f'BortStack enquiry: {service}',
'text': text, 'html': '<pre>' + escape(text) + '</pre>'}
try:
deliver(payload, key, app.config)
except Exception:
# No provider exception/body or visitor data in logs/responses.
app.logger.warning('Contact provider acceptance could not be confirmed')
return {'message': 'Sending could not be confirmed. Your draft is kept; please retry. A retry of the same draft avoids duplicate processing.'}, 503
return {'success': True, 'message': 'Your enquiry has been accepted for delivery. Thank you.'}
return app
app = create_app()
+103
View File
@@ -0,0 +1,103 @@
"""Standalone tests: no tests/conftest.py or account/database fixture required."""
import json
from uuid import uuid4
from unittest.mock import patch
import pytest
from contact_app import create_app, deliver
VALID = dict(name='Example Person', email='person@example.com', service='',
description='A useful software project enquiry.', website='')
KEY = str(uuid4())
@pytest.fixture
def app():
return create_app(dict(TESTING=True, EMAIL_DELIVERY_ENABLED=True,
EMAIL_FROM='BortStack <verified@example.com>',
CONTACT_EMAIL='business@example.com', RESEND_API_KEY='test-only'))
def post(app, data=VALID, key=KEY):
return app.test_client().post('/api/contact', json=data, headers={'Idempotency-Key': key})
def test_independent_no_database_or_account_routes(app):
assert 'sqlalchemy' not in app.extensions
assert app.test_client().get('/api/health/ready').status_code == 200
assert app.test_client().get('/api/users').status_code == 404
assert app.test_client().get('/api/contact/config').json == {'email': 'business@example.com', 'available': True}
def test_success_safe_sender_replyto_and_escaping(app):
with patch('contact_app.deliver') as send:
r = post(app, {**VALID, 'name': '<script>Example</script>'})
assert r.status_code == 200 and r.json['success'] is True
payload, key, _ = send.call_args.args
assert payload['from'] == 'BortStack <verified@example.com>'
assert payload['reply_to'] == VALID['email']
assert payload['to'] == ['business@example.com']
assert '<script>' not in payload['html']
assert key == KEY
@pytest.mark.parametrize('change', [dict(name=''), dict(name='x'*101), dict(name='x\r\nBcc:x@y.com'),
dict(email='a@example.com\r\nBcc:x@y.com'), dict(email='not-an-email'), dict(email='a@localhost'),
dict(description='short'), dict(description='x'*5001), dict(service='Unknown'),
dict(name=['bad']), dict(email=None), dict(company='not allowed'), dict(website='bot')])
def test_invalid_does_not_send(app, change):
with patch('contact_app.deliver') as send:
assert post(app, {**VALID, **change}).status_code == 400
send.assert_not_called()
@pytest.mark.parametrize('data', [[], 'text', 42, None])
def test_json_shape(app, data):
assert post(app, data).status_code == 400
def test_payload_limit(app):
assert post(app, {**VALID, 'description': 'x'*40000}).status_code == 413
@pytest.mark.parametrize('config', [dict(EMAIL_DELIVERY_ENABLED=False), dict(RESEND_API_KEY=''),
dict(EMAIL_FROM=''), dict(EMAIL_FROM='x@y.com\r\nBcc:z@y.com'), dict(CONTACT_EMAIL='invalid')])
def test_disabled_or_unconfigured_never_claims_success(app, config):
app.config.update(config)
with patch('contact_app.deliver') as send:
assert post(app).status_code == 503
assert app.test_client().get('/api/contact/config').json['available'] is False
send.assert_not_called()
def test_missing_key(app):
assert post(app, key='').status_code == 400
def test_provider_failure_generic_no_payload_log(app, caplog):
with patch('contact_app.deliver', side_effect=RuntimeError('private provider detail')):
r = post(app)
assert r.status_code == 503
assert 'private provider detail' not in r.text + caplog.text
assert VALID['email'] not in caplog.text
assert VALID['description'] not in caplog.text
def test_rate_limit(app):
with patch('contact_app.deliver'):
responses = [post(app) for _ in range(6)]
assert [r.status_code for r in responses] == [200]*5 + [429]
assert responses[-1].headers['Retry-After'] == '3600'
def test_provider_contract_timeout_and_idempotency(app):
with patch('contact_app.urlopen') as url:
url.return_value.__enter__.return_value.read.return_value = b'{"id":"accepted"}'
deliver({'from':'verified@example.com'}, KEY, app.config)
req = url.call_args.args[0]
assert url.call_args.kwargs['timeout'] == 10
assert req.get_header('Idempotency-key') == 'contact/' + KEY
assert json.loads(req.data) == {'from':'verified@example.com'}
with patch('contact_app.urlopen') as url:
url.return_value.__enter__.return_value.read.return_value = b'{}'
with pytest.raises(ValueError):
deliver({}, KEY, app.config)