Files

187 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""Exercise the actual list reader, cache pairing, signed header parser and text inflater."""
from pathlib import Path
import subprocess
import tempfile
import zlib
source = Path(__file__).with_name('OctoUpdater.cpp').read_text()
def section(start, stop):
return source[source.index(start):source.index(stop)]
prelude = r'''
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <cwchar>
#include <deque>
#include <filesystem>
#include <fstream>
#include <initializer_list>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <zlib.h>
#include "current_files.hpp"
namespace fs=std::filesystem;
using DWORD=uint32_t;
#define _wcsicmp wcscasecmp
struct Fail:std::runtime_error{using std::runtime_error::runtime_error;};
void Sleep(unsigned){}
void say(const char*,...){}
'''
network = r'''
std::deque<std::pair<std::string,std::string>> script;
fs::path g_work;
std::string g_base;
std::string get_text(const std::string& path,bool compressed=true){
assert(!script.empty() && path==script.front().first);
assert(compressed!=path.ends_with(".sig"));
auto reply=script.front().second;
script.pop_front();
if(reply.starts_with("http:")) throw HttpError(reply,std::stoul(reply.substr(5)));
return reply;
}
std::vector<uint8_t> read_all(const fs::path& p){
std::ifstream f(p,std::ios::binary);return {std::istreambuf_iterator<char>(f),{}};
}
std::string fixture_signature(const std::string& body){
if(!body.starts_with("OCTO-PATCH")) return "signed:"+body;
auto digest=crc32(0,reinterpret_cast<const Bytef*>(body.data()),body.size());
std::string raw;
for(unsigned i=0;i<4;i++) raw.push_back(char(digest>>(8*i)));
return raw;
}
bool verify(const std::string& body,const std::string& signature){return signature==fixture_signature(body);}
'''
cases = r'''
int main(){
const std::string compact="manifest-store.txt", legacy="manifest.txt", sig=compact+".sig";
auto failure=[] { bool threw=false;try{fetch_signed_list();}catch(const Fail&){threw=true;}assert(threw && script.empty()); };
script={{sig,"signed:A"},{compact,"A"}};
assert(fetch_signed_list().body=="A" && script.empty());
script={{sig,"http:404"},{legacy+".sig","signed:B"},{legacy,"B"}};
assert(fetch_signed_list().body=="B" && script.empty());
script={{sig,"http:403"}};failure();
script={{sig,"http:503"}};failure();
script={{sig,"http:410"},{legacy+".sig","http:404"}};failure();
script={{sig,"signed:A"},{compact,"http:404"},{legacy+".sig","signed:C"},{legacy,"C"}};
assert(fetch_signed_list().body=="C" && script.empty());
script={{sig,"bad"},{compact,"A"},{sig,"bad"},{compact,"A"},{legacy+".sig","signed:B"},{legacy,"B"}};
assert(fetch_signed_list().name==legacy && script.empty());
script={{sig,"bad"},{compact,"A"},{sig,"bad"},{compact,"A"},{legacy+".sig","bad"},{legacy,"C"},{legacy+".sig","bad"},{legacy,"C"}};failure();
script={{sig,"signed:A"},{compact,"B"},{sig,"signed:B"}};
assert(fetch_signed_list().body=="B" && script.empty());
std::ofstream(compact).write("cached",6);std::ofstream(sig).write("signed:cached",13);
script={{sig,"signed:cached"}};
assert(fetch_signed_list().body=="cached" && script.empty());
std::ofstream(compact)<<"tampered";script={{sig,"signed:cached"},{compact,"cached"}};
assert(fetch_signed_list().body=="cached" && script.empty());
std::string header="OCTO-PATCH 1\nCHANNEL octo\n";
std::string marker;
parse(header+"LEGACY-SIGNATURE 00ff\nEND\n",&marker,2,"octo");
assert(marker.size()==2 && uint8_t(marker[0])==0 && uint8_t(marker[1])==255);
parse(header+"END\n",nullptr,2,"octo");
for(std::string bad:{"","LEGACY-SIGNATURE 0xz1\n","LEGACY-SIGNATURE ff\n","LEGACY-SIGNATURE aabb\nLEGACY-SIGNATURE ccdd\n"}){
marker.clear();bool threw=false;
try{parse(header+bad+"END\n",&marker,2,"octo");}catch(const Fail&){threw=true;}
assert(threw);
}
marker.clear();bool bad_channel=false;
try{parse(header+"LEGACY-SIGNATURE aabb\nEND\n",&marker,2,"local");}catch(const Fail&){bad_channel=true;}
assert(bad_channel);
for(const std::string invalid:{"OCTO-PATCH 1\nEND\n", "OCTO-PATCH 1\nCHANNEL other\nEND\n",
"OCTO-PATCH 1\nCHANNEL octo\nCHANNEL octo\nEND\n", "OCTO-PATCH 1\nSTEP FILES f\nCHANNEL octo\nEND\n"}){
bool failed=false;try{parse(invalid,nullptr,4,"octo");}catch(const Fail&){failed=true;}assert(failed);
}
{
g_work="history";fs::create_directory(g_work);
auto cache=[](const char* path,const std::string& data){std::ofstream(g_work/path,std::ios::binary)<<data;};
const std::string first="STEP FILES initial\nPUT shared A 1 blob 1 any\nPUT Retired/old A 1 old 1 any\n";
const std::string content="STEP CONTENT old-layout parent child\n";
const std::string store="STEP STORE portable-layout parent child\nFRAME hash data\n";
const std::string newest="STEP FILES replace\nPUT shared B 1 next 1 any\n";
const std::string retirement="STEP POLICY retired-paths\nRETIRE Retired/\n";
auto legacy_body=[&](const std::string& rows){return header+rows+"END\n";};
auto compact_body=[&](const std::string& rows,const std::string& sig){
std::string hex;for(unsigned char c:sig){hex+="0123456789abcdef"[c>>4];hex+="0123456789abcdef"[c&15];}
return header+"LEGACY-SIGNATURE "+hex+"\n"+rows+"END\n";
};
auto check=[&](const std::string& rows,const std::string& legacy_rows,bool is_compact,bool ok){
const auto signature=fixture_signature(legacy_body(legacy_rows));
const auto body=is_compact?compact_body(rows,signature):legacy_body(legacy_rows);
std::string bound;
auto view=parse(body,is_compact?&bound:nullptr,4,"octo");
bool failed=false;
try{check_committed_list(view,is_compact?bound:signature,is_compact,"octo");}catch(const Fail&){failed=true;}
assert(failed!=ok);
};
const auto old_rows=first+content;
const auto current_rows=retirement+first+content+newest+store;
const auto compact_rows=retirement+first+store+newest+store;
const auto old_sig=fixture_signature(legacy_body(old_rows));
const auto current_sig=fixture_signature(legacy_body(current_rows));
cache("applied.txt","obsolete-unpublished-id\n");
check("",old_rows,false,true); // no completed manifest (fresh / interrupted first install)
cache("manifest.txt.sig",old_sig);
cache("manifest.txt",legacy_body(old_rows));
check(compact_rows,current_rows,true,true); // STORE retrofit, new retirement, new FILES step
check("",current_rows,false,true);
cache("manifest.txt.sig",current_sig);
auto completed=compact_body(compact_rows,current_sig);
cache("manifest-store.txt",completed);
cache("manifest-store.txt.sig",fixture_signature(completed));
for(bool compact_view:{false,true}){
check(old_rows,old_rows,compact_view,false);
const auto unretired=first+store+newest;
check(unretired,unretired,compact_view,false); // same step IDs, missing retirement
const auto dropped=retirement+first+store;
check(dropped,dropped,compact_view,false);
const auto reordered=retirement+newest+first+store;
check(reordered,reordered,compact_view,false);
const auto missing_store=retirement+first+content+newest;
check(missing_store,missing_store,compact_view,false);
const auto rewritten=compact_rows+"STEP FILES unrelated\n";
auto changed=rewritten;changed.replace(changed.find("shared B"),8,"shared C");
check(changed,changed,compact_view,false);
check(compact_rows+"STEP FILES next\n",current_rows+"STEP FILES next\n",compact_view,true);
}
cache("manifest-store.txt","tampered");
cache("manifest.txt",legacy_body(current_rows)); // authenticate legacy with the successful marker itself
check("",old_rows,false,false);
fs::remove(g_work/"manifest.txt");
check("",current_rows,false,true); // authenticated same generation, no old body needed
check("",old_rows,false,false); // changed legacy fallback with missing/damaged completed cache
check(compact_rows+"STEP FILES next\n",current_rows+"STEP FILES next\n",true,true); // marker-only migration
}
std::string text=header+"END\n";
for(auto name:{L"gzip",L"deflate"}){
std::string codec=name==std::wstring(L"gzip")?"gzip":"deflate";
auto bin=read_all(codec);
std::string packed(bin.begin(),bin.end());
for(bool automatic:{true,false}) assert(decode_text(packed,{automatic,name})==text);
assert(decode_text(text,{true,name})==text);
bool failed=false;try{decode_text(packed.substr(0,packed.size()-1),{false,name});}catch(const Fail&){failed=true;}
assert(failed);
}
}
'''
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
text = b'OCTO-PATCH 1\nCHANNEL octo\nEND\n'
for name, bits in [('gzip',31),('deflate',15)]:
encoder = zlib.compressobj(wbits=bits)
(root/name).write_bytes(encoder.compress(text) + encoder.flush())
code = (prelude + section('struct HttpError', 'template <class Sink>') +
section('static constexpr size_t MaxTextBytes', '// A fresh URL per network attempt') +
section('struct Step {', 'static std::string g_base') + network +
section('struct SignedList {', 'static void save_list_cache') + cases)
(root/'check.cpp').write_text(code)
subprocess.run(['c++','-std=c++20','-I',str(Path(__file__).resolve().parent),'check.cpp','-lz','-o','check'],cwd=root,check=True)
subprocess.run(['./check'],cwd=root,check=True)
print('Compact/legacy selection, channel binding, authenticated rollback guards, rotation and HTTP gzip/deflate passed.')