chore: qualify restricted publishing smoke gates and legacy AJAX compatibility
This commit is contained in:
parent
27bc77b40a
commit
a680aa3bd8
@ -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,
|
The root-owned helper locks its own target, snapshots/verifies untrusted input,
|
||||||
installs immutable files, atomically switches `current`, restarts only its own service,
|
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
|
failed switch with a previous release, restore that previous website. No SQL rollback
|
||||||
is involved. Receipts: `/opt/plotdirector-website-dev/receipts/*.json`; current marker
|
is involved. Receipts: `/opt/plotdirector-website-dev/receipts/*.json`; current marker
|
||||||
`active-deployment.json`; releases under `releases/RELEASE-ID/app`. Signing is separate
|
`active-deployment.json`; releases under `releases/RELEASE-ID/app`. Signing is separate
|
||||||
|
|||||||
@ -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])
|
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)
|
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')
|
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']:
|
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(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('/hubs/echo',headers={'Connection':'Upgrade','Upgrade':'websocket'});assert r.code==101;checks.append('legacy websocket upgrade reaches application')
|
||||||
|
|||||||
@ -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
|
output=self.root/'bundle';release.compress_bundle(raw,output,self.key,self.public,verified=True);return output
|
||||||
def verify(self,bundle):
|
def verify(self,bundle):
|
||||||
with tempfile.TemporaryDirectory() as temp:return release.verify(bundle,Path(temp),self.public)[0]
|
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_valid_compressed_release(self):self.assertEqual(self.verify(self.bundle())['product'],'PlotDirector.Website')
|
||||||
def test_wrong_product(self):
|
def test_wrong_product(self):
|
||||||
with self.assertRaises(Exception):self.verify(self.bundle(product='PlotLine'))
|
with self.assertRaises(Exception):self.verify(self.bundle(product='PlotLine'))
|
||||||
|
|||||||
@ -48,8 +48,22 @@ server {
|
|||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
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))(?:/|$) {
|
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;
|
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.
|
# Retain original public Help and solver URLs, including legacy help redirects.
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://127.0.0.1:5004;
|
proxy_pass http://127.0.0.1:5004;
|
||||||
|
|||||||
@ -2,11 +2,22 @@
|
|||||||
"""Website-only signed releases. No database worker, application target or shell hooks."""
|
"""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
|
import argparse,fcntl,json,os,re,shutil,subprocess,sys,tarfile,tempfile,time,uuid
|
||||||
from pathlib import Path
|
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'))
|
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 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
|
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<len(data)<=limit,'Unexpected or oversized smoke response')
|
||||||
|
return data
|
||||||
|
|
||||||
BUNDLE={'authorization.json','authorization.sig','transport.json','transport.sig','package.tar.zst'}
|
BUNDLE={'authorization.json','authorization.sig','transport.json','transport.sig','package.tar.zst'}
|
||||||
def sign(path,key):
|
def sign(path,key):
|
||||||
subprocess.run(['/usr/bin/openssl','pkeyutl','-sign','-inkey',str(key),'-rawin','-in',str(path),'-out',str(Path(path).with_suffix('.sig'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
subprocess.run(['/usr/bin/openssl','pkeyutl','-sign','-inkey',str(key),'-rawin','-in',str(path),'-out',str(Path(path).with_suffix('.sig'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
@ -105,12 +116,15 @@ def activate(release,validate=False,rollback=False):
|
|||||||
ready=False
|
ready=False
|
||||||
for _ in range(40):
|
for _ in range(40):
|
||||||
try:
|
try:
|
||||||
with urlopen(cfg['url'],timeout=2) as response:health=json.load(response)
|
health=json.loads(response_bytes(cfg['url'],16384))
|
||||||
if health.get('healthy') and health.get('product')=='PlotDirector.Website' and health.get('sourceCommit')==m['source_commit']:ready=True;break
|
if health.get('healthy') and health.get('product')=='PlotDirector.Website' and health.get('sourceCommit')==m['source_commit']:ready=True;break
|
||||||
except (OSError,ValueError):pass
|
except (OSError,ValueError):pass
|
||||||
time.sleep(.25)
|
time.sleep(.25)
|
||||||
require(ready,'Website health/source identity failed')
|
require(ready,'Website health/source identity failed')
|
||||||
receipt['health']=health
|
receipt['health']=health
|
||||||
|
base=cfg['url'].removesuffix('/health')
|
||||||
|
receipt['smokeTests']=[{'path':path,'status':200,'bytes':len(response_bytes(base+path,1024**2))}
|
||||||
|
for path in ['/','/pricing','/help','/problem-solver','/sitemap.xml']]
|
||||||
(root/'active-deployment.json').write_bytes(canonical(receipt|{'status':'activated'}))
|
(root/'active-deployment.json').write_bytes(canonical(receipt|{'status':'activated'}))
|
||||||
receipt['status']='validated' if validate else 'activated'
|
receipt['status']='validated' if validate else 'activated'
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -119,6 +133,9 @@ def activate(release,validate=False,rollback=False):
|
|||||||
link=root/('.recover-'+receipt['operation']);link.symlink_to(previous);os.replace(link,root/'current')
|
link=root/('.recover-'+receipt['operation']);link.symlink_to(previous);os.replace(link,root/'current')
|
||||||
subprocess.run(['/usr/bin/systemctl','restart',cfg['service']],check=False,timeout=30)
|
subprocess.run(['/usr/bin/systemctl','restart',cfg['service']],check=False,timeout=30)
|
||||||
receipt['recoveredPrevious']=True
|
receipt['recoveredPrevious']=True
|
||||||
|
elif switched:
|
||||||
|
subprocess.run(['/usr/bin/systemctl','stop',cfg['service']],check=False,timeout=30)
|
||||||
|
receipt['failedInitialServiceStopped']=True
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
receipt['completedUtc']=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
|
receipt['completedUtc']=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user