PlotDirector.Website/Tests/nginx_compatibility.py

59 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""Qualify prepared vhosts in an unprivileged local Nginx/TLS sandbox, not Production."""
import http.server,json,pathlib,socket,ssl,subprocess,tempfile,threading,time,urllib.request,urllib.error,hashlib
ROOT=pathlib.Path(__file__).resolve().parents[1]
class Backend(http.server.BaseHTTPRequestHandler):
def log_message(self,*a):pass
def do_GET(self):
if self.headers.get('Upgrade','').lower()=='websocket':
self.send_response(101);self.send_header('Upgrade','websocket');self.send_header('Connection','upgrade');self.end_headers();return
self.send_response(200);self.end_headers();self.wfile.write(self.server.name.encode())
def do_POST(self):
body=self.rfile.read(int(self.headers.get('Content-Length','0')));self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'backend':self.server.name,'path':self.path,'bodySha256':hashlib.sha256(body).hexdigest(),'authorization':self.headers.get('Authorization')}).encode())
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self,*args):return None
def port():
with socket.socket() as s:s.bind(('127.0.0.1',0));return s.getsockname()[1]
checks=[]
with tempfile.TemporaryDirectory(prefix='pd-nginx-qualification-') as directory:
temp=pathlib.Path(directory);http_port,https_port=port(),port();backends=[]
for name in ['app','website']:
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Backend);server.name=name;threading.Thread(target=server.serve_forever,daemon=True).start();backends.append(server)
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-subj','/CN=localhost','-addext','subjectAltName=IP:127.0.0.1,DNS:plotdirector.com,DNS:app.plotdirector.com,DNS:www.plotdirector.com','-keyout',str(temp/'key.pem'),'-out',str(temp/'cert.pem')],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
snippets=[]
for name in ['nginx-website.conf','nginx-application.conf']:
text=(ROOT/'Tools/Deployment/production'/name).read_text()
import re
text=re.sub(r'listen 80;',f'listen 127.0.0.1:{http_port};',text);text=re.sub(r'listen \[::\]:80;','',text)
text=re.sub(r'listen 443 ssl;',f'listen 127.0.0.1:{https_port} ssl;',text);text=re.sub(r'listen \[::\]:443 ssl;','',text)
text=re.sub(r'/etc/letsencrypt/live/[^/]+/fullchain.pem',str(temp/'cert.pem'),text);text=re.sub(r'/etc/letsencrypt/live/[^/]+/privkey.pem',str(temp/'key.pem'),text)
text=text.replace('127.0.0.1:5001',f'127.0.0.1:{backends[0].server_port}').replace('127.0.0.1:5004',f'127.0.0.1:{backends[1].server_port}')
text=re.sub(r'/var/log/nginx/([^;]+)',lambda m:str(temp/m[1]),text);snippets.append(text)
(temp/'nginx.conf').write_text(f'pid {temp}/nginx.pid;\nerror_log {temp}/error.log;\nevents {{}}\nhttp {{\naccess_log off;\n'+''.join(snippets)+'\n}\n')
result=subprocess.run(['nginx','-t','-p',str(temp)+'/', '-c',str(temp/'nginx.conf')],capture_output=True);assert result.returncode==0,result.stderr.decode();checks.append('both prepared vhosts pass nginx -t')
nginx=subprocess.Popen(['nginx','-p',str(temp)+'/', '-c',str(temp/'nginx.conf'),'-g','daemon off;'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
ctx=ssl.create_default_context(cafile=str(temp/'cert.pem'));opener=urllib.request.build_opener(NoRedirect(),urllib.request.HTTPSHandler(context=ctx))
def request(path,host='plotdirector.com',data=None,headers=None):
req=urllib.request.Request(f'https://127.0.0.1:{https_port}'+path,headers={'Host':host,**(headers or {})},data=data)
try:return opener.open(req,timeout=5)
except urllib.error.HTTPError as e:return e
for _ in range(50):
try:r=request('/');break
except OSError:time.sleep(.1)
assert r.read()==b'website';checks.append('public root goes to independent website')
for path in ['/Projects/Details/123?focus=4','/Account/ResetPassword?token=test','/problem-solver/workspace/characters','/admin/writing-solver','/onboarding']:
r=request(path);assert r.code==308 and r.headers['Location']=='https://app.plotdirector.com'+path;checks.append('legacy browser path/query '+path.split('?')[0])
body=b'{"synthetic":"request body preserved"}';r=request('/api/probe?x=y',data=body,headers={'Authorization':'Bearer SYNTHETIC-TEST-ONLY'});payload=json.load(r)
assert payload=={'backend':'app','path':'/api/probe?x=y','bodySha256':hashlib.sha256(body).hexdigest(),'authorization':'Bearer SYNTHETIC-TEST-ONLY'};checks.append('legacy API preserves POST body query and bearer header')
for path in ['/js/word-companion-host.js?v=legacy','/css/word-companion.css','/android-chrome-192x192.png']:
r=request(path);assert r.read()==b'app';checks.append('legacy taskpane asset '+path.split('?')[0])
r=request('/hubs/echo',headers={'Connection':'Upgrade','Upgrade':'websocket'});assert r.code==101;checks.append('legacy websocket upgrade reaches application')
r=request('/HelpDrawer/Image?file=approved.png');assert r.read()==b'website';r=request('/HelpDrawer/Article?key=projects.overview');assert r.read()==b'website';checks.append('published help images and fragments stay independent of the application')
r=request('/Projects',host='app.plotdirector.com');assert r.read()==b'app' and 'noindex' in r.headers['X-Robots-Tag'];checks.append('application host and noindex isolated')
assert request('/_deployment/health').code==404 and request('/_deployment/health',host='app.plotdirector.com').code==404;checks.append('health endpoint denied on both public hosts')
print(json.dumps({'passed':True,'sandboxOnly':True,'checks':checks},indent=2))
finally:
nginx.terminate();nginx.wait(timeout=10)
for server in backends:server.shutdown();server.server_close()