diff --git a/Docs/Publishing.md b/Docs/Publishing.md index 2d82d29..de4522c 100644 --- a/Docs/Publishing.md +++ b/Docs/Publishing.md @@ -56,7 +56,8 @@ Website manifests contain no SQL; this helper never invokes a database worker. The root-owned helper locks its own target, snapshots/verifies untrusted input, installs immutable files, atomically switches `current`, restarts only its own service, -and checks health/product/source identity. Failures record receipts and, after a +and checks health/product/source identity plus the homepage, pricing, help, solver and +sitemap through bounded, non-redirecting loopback smoke requests. Failures record receipts and, after a failed switch with a previous release, restore that previous website. No SQL rollback is involved. Receipts: `/opt/plotdirector-website-dev/receipts/*.json`; current marker `active-deployment.json`; releases under `releases/RELEASE-ID/app`. Signing is separate diff --git a/Tests/nginx_compatibility.py b/Tests/nginx_compatibility.py index 084f1ae..5967f2c 100644 --- a/Tests/nginx_compatibility.py +++ b/Tests/nginx_compatibility.py @@ -46,6 +46,10 @@ with tempfile.TemporaryDirectory(prefix='pd-nginx-qualification-') as directory: 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') + r=request('/Appearance/Theme',data=body,headers={'Authorization':'Bearer SYNTHETIC-TEST-ONLY'});payload=json.load(r);assert payload['backend']=='app' and payload['bodySha256']==hashlib.sha256(body).hexdigest();checks.append('legacy controller POST preserves body without cross-origin redirect') + for headers in [{'X-Requested-With':'XMLHttpRequest'},{'Accept':'application/json'}]: + r=request('/Scenes/Details/123',headers=headers);assert r.read()==b'app' + checks.append('legacy AJAX and JSON GET reach application without browser redirect') 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') diff --git a/Tests/test_deployment.py b/Tests/test_deployment.py index e52aaf4..0686bbb 100644 --- a/Tests/test_deployment.py +++ b/Tests/test_deployment.py @@ -25,6 +25,27 @@ class SignedReleaseTests(unittest.TestCase): output=self.root/'bundle';release.compress_bundle(raw,output,self.key,self.public,verified=True);return output def verify(self,bundle): with tempfile.TemporaryDirectory() as temp:return release.verify(bundle,Path(temp),self.public)[0] + def health_server(self): + import http.server,threading + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self,*args):pass + def do_GET(self): + if self.path=='/redirect':self.send_response(302);self.send_header('Location','/ok');self.end_headers();return + self.send_response(200);self.end_headers();self.wfile.write(b'0123456789abcdef') + server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler);threading.Thread(target=server.serve_forever,daemon=True).start();return server + def test_smoke_redirect_refused(self): + server=self.health_server() + try: + with self.assertRaises(Exception):release.response_bytes(f'http://127.0.0.1:{server.server_port}/redirect',64) + finally:server.shutdown();server.server_close() + def test_oversized_smoke_response_refused(self): + server=self.health_server() + try: + with self.assertRaises(Exception):release.response_bytes(f'http://127.0.0.1:{server.server_port}/ok',8) + self.assertEqual(release.response_bytes(f'http://127.0.0.1:{server.server_port}/ok',16),b'0123456789abcdef') + finally:server.shutdown();server.server_close() + def test_external_smoke_target_refused(self): + with self.assertRaises(Exception):release.response_bytes('https://example.invalid/',64) def test_valid_compressed_release(self):self.assertEqual(self.verify(self.bundle())['product'],'PlotDirector.Website') def test_wrong_product(self): with self.assertRaises(Exception):self.verify(self.bundle(product='PlotLine')) diff --git a/Tools/Deployment/production/nginx-website.conf b/Tools/Deployment/production/nginx-website.conf index 06a0eda..7d09f95 100644 --- a/Tools/Deployment/production/nginx-website.conf +++ b/Tools/Deployment/production/nginx-website.conf @@ -48,8 +48,22 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } location ~* ^/(Acceptance|Account|Admin|Ai|AiAdministration|Analytics|Appearance|Archives|BookRecovery|Books|Chapters|CharacterAttributes|CharacterWorkspace|Characters|ContextNames|ContextNavigation|ContextRelationshipLenses|ContextTools|ContinuityExplorer|DeploymentHealth|Dynamics|Exports|FeatureRequests|FloorPlans|Geography|HelpDiagnostics|HelpDrawer|Imports|IntelligenceReview|IntentAssessment|InvestigationCompanion|LocationWorkspace|Locations|ManageAccount|ManuscriptReader|Maps|NameVerification|Names|NarrativeFocus|NativeChapterSync|NativeCompanion|NativeCompanionAuth|NativeCompanionWorkflow|NativeInstallation|NativeManuscriptCapture|NativePresence|NativeWorkspace|Onboarding|ParagraphManuscript|PlotLineWorkspace|PlotLines|PlotThreads|ProjectCollaborators|ProjectMetrics|ProjectRestorePoints|Projects|RelationshipMap|Scenarios|SceneMetrics|Scenes|SharedFocus|SpatialContext|StoryAssets|StoryBible|StoryCalendar|StoryPoint|StripeWebhook|Timeline|Toolbar|Warnings|WordCompanion|WordCompanionHost|Writer|WriterActivities|WriterAuthoring|WriterInvestigations|WriterPlanning|WriterReview|WriterWord|WriterWork|Writing|WritingActivity|WritingSolverAdmin|WritingSolverReview|WritingSolverWorkspace|admin|intelligence-review|manuscript|onboarding|InvestigationCompanion|problem-solver/workspace|writing-problems/workspace|Home|Pricing/(?:StartTrial|Checkout))(?:/|$) { + # Named-location forwarding preserves method/body for legacy AJAX and API-like + # controller actions. Only normal browser GET/HEAD navigation redirects. + error_page 418 = @plotdirector_legacy_application; + if ($request_method !~ ^(GET|HEAD)$) { return 418; } + if ($http_x_requested_with = XMLHttpRequest) { return 418; } + if ($http_accept ~* application/json) { return 418; } return 308 https://app.plotdirector.com$request_uri; } + location @plotdirector_legacy_application { + proxy_pass http://127.0.0.1:5001; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + add_header X-Robots-Tag "noindex, nofollow" always; + } # Retain original public Help and solver URLs, including legacy help redirects. location / { proxy_pass http://127.0.0.1:5004; diff --git a/Tools/Deployment/website_release.py b/Tools/Deployment/website_release.py index 3acda0e..54e4de3 100644 --- a/Tools/Deployment/website_release.py +++ b/Tools/Deployment/website_release.py @@ -2,11 +2,22 @@ """Website-only signed releases. No database worker, application target or shell hooks.""" import argparse,fcntl,json,os,re,shutil,subprocess,sys,tarfile,tempfile,time,uuid from pathlib import Path -from urllib.request import urlopen +from urllib.request import build_opener, HTTPRedirectHandler sys.path.insert(0,str(Path(__file__).resolve().parent/'vendor')) from release import canonical,file_digest,load,require,safe_name,safe_path,snapshot,LIMIT_BYTES,LIMIT_FILES from transport import compress_bundle,envelope,decompress,signed_json +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self,*args):return None + +HTTP=build_opener(NoRedirect()) +def response_bytes(url,limit): + require(url.startswith('http://127.0.0.1:'),'Health must remain on loopback') + with HTTP.open(url,timeout=3) as response: + data=response.read(limit+1) + require(response.status==200 and 0