diff --git a/website/ops/publish-cookbook-route.py b/website/ops/publish-cookbook-route.py new file mode 100644 index 00000000..af672735 --- /dev/null +++ b/website/ops/publish-cookbook-route.py @@ -0,0 +1,37 @@ +"""Route the cookbook to the current tested application instead of an old static copy.""" +import argparse,hashlib,importlib.util,json,os,re,urllib.request +from pathlib import Path +spec=importlib.util.spec_from_file_location('shared',Path(__file__).with_name('publish-shared-design-route.py'));shared=importlib.util.module_from_spec(spec);spec.loader.exec_module(shared) +CURRENT=Path('/home/dunerealms/apps/dunerealms/current') +TARGET=Path('/etc/nginx/snippets/dunerealms-cookbook-e40883ba.conf') +LEGACY='/var/www/dunerealms-cookbook-e40883ba/' +FILES=('imperial-recipe-book.html','lets-play.html','imperial-recipe-book.css','imperial-recipe-book.js','recipe-catalogue.json') +IDS={'dunechest_'+name for name in ('ender_chest','speed_hopper_1','speed_hopper_2','speed_hopper_3','auto_crafter','wrench')} +def route_content(old): + for suffix in (*FILES,'recipe-icons/'): + prefix='^~' if suffix.endswith('/') else '=' + route=f'location {prefix} /{suffix} {{\n proxy_pass http://127.0.0.1:3100;\n proxy_set_header Host www.dunerealms.com;\n add_header Cache-Control "no-cache" always;\n}}' + matches=list(re.finditer(r'location\s+'+re.escape(prefix)+r'\s*/'+re.escape(suffix)+r'\s*\{[^{}]*\}',old)) + if len(matches)!=1:raise ValueError('Unknown or duplicate cookbook route: '+suffix) + match=matches[0] + if match[0]==route:continue + if not re.search(r'alias\s+'+re.escape(LEGACY+suffix)+r'\s*;',match[0]):raise ValueError('Cookbook route is not the verified legacy alias') + old=old[:match.start()]+route+old[match.end():] + return old +def validate_catalogue(payload): + recipes=json.loads(payload);found={r['id']:r for r in recipes if r.get('id') in IDS} + if set(found)!=IDS or any(len(r.get('grid',[]))!=9 for r in found.values()):raise ValueError('Current built cookbook is incomplete') + return len(recipes) +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--expected-release',required=True);parser.add_argument('--apply',action='store_true');parser.add_argument('--plan-hash');args=parser.parse_args() + if not re.fullmatch('[a-f0-9]{40}',args.expected_release) or CURRENT.resolve().name!='ci-'+args.expected_release:raise ValueError('Active built release changed') + request=urllib.request.Request('http://127.0.0.1:3100/recipe-catalogue.json',headers={'Host':'www.dunerealms.com'}) + with urllib.request.urlopen(request,timeout=15) as response:payload=response.read(1000000) + count=validate_catalogue(payload);old=TARGET.read_text();new=route_content(old);sha=lambda b:hashlib.sha256(b).hexdigest() + plan={'release':args.expected_release,'target':str(TARGET),'before':sha(old.encode()),'after':sha(new.encode()),'catalogueSha256':sha(payload),'recipes':count} + digest=sha(json.dumps(plan,sort_keys=True).encode());print(json.dumps({**plan,'planHash':digest,'applied':False})) + if args.apply: + if os.getuid()!=0 or args.plan_hash!=digest:raise ValueError('Root and matching reviewed plan required') + backup=Path('/home/dunerealms/backups/cookbook-route-'+args.expected_release)/TARGET.name + changed=shared.replace_config(TARGET,new,backup);print(json.dumps({'applied':True,'changed':changed,'backup':str(backup)})) +if __name__=='__main__':main() diff --git a/website/ops/test_cookbook_route.py b/website/ops/test_cookbook_route.py new file mode 100644 index 00000000..383cff2d --- /dev/null +++ b/website/ops/test_cookbook_route.py @@ -0,0 +1,16 @@ +import importlib.util,json,unittest +from pathlib import Path +spec=importlib.util.spec_from_file_location('book',Path(__file__).with_name('publish-cookbook-route.py'));book=importlib.util.module_from_spec(spec);spec.loader.exec_module(book) +class CookbookRoute(unittest.TestCase): + def original(self):return '\n'.join('location '+('^~' if p.endswith('/') else '=')+' /'+p+' { alias '+book.LEGACY+p+'; }' for p in (*book.FILES,'recipe-icons/'))+'\n'+book.shared.ROUTE + def test_routes_entire_cookbook_and_preserves_shared_design(self): + after=book.route_content(self.original());self.assertEqual(after.count('proxy_pass http://127.0.0.1:3100;'),6);self.assertIn(book.shared.ROUTE,after);self.assertEqual(book.route_content(after),after) + def test_unknown_or_duplicate_route_is_refused(self): + for old in ('',self.original().replace(book.LEGACY+'recipe-catalogue.json','/unexpected.json'),self.original()+'\nlocation = /recipe-catalogue.json {}'): + with self.assertRaises(ValueError):book.route_content(old) + def test_old_catalogue_or_missing_recipe_grid_is_refused(self): + recipes=[{'id':key,'grid':[None]*9} for key in book.IDS];self.assertEqual(book.validate_catalogue(json.dumps(recipes)),6) + with self.assertRaises(ValueError):book.validate_catalogue('[]') + recipes[0]['grid']=[] + with self.assertRaises(ValueError):book.validate_catalogue(json.dumps(recipes)) +if __name__=='__main__':unittest.main()