diff --git a/.github/workflows/porter-windows.yml b/.github/workflows/porter-windows.yml new file mode 100644 index 000000000..ecc12d47f --- /dev/null +++ b/.github/workflows/porter-windows.yml @@ -0,0 +1,27 @@ +name: Porter Windows service + +on: + pull_request: + paths: + - .github/workflows/porter-windows.yml + - tools/os64serve.py + - tools/porter_store.py + - tools/test_porter.py + +permissions: + contents: read + +jobs: + loopback: + runs-on: windows-2022 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: python -m unittest discover -s tools -p test_porter.py -k FileSnapshotTests + - run: | + for ($attempt = 1; $attempt -le 12; $attempt++) { + python -m unittest discover -s tools -p test_porter.py -k LoopbackTests + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } diff --git a/GNUmakefile b/GNUmakefile index a19f73b1b..de7608524 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -550,7 +550,55 @@ ICON_ASSETS := $(sort $(wildcard $(ICON_ASSET_DIR)/*.png)) ICON_MANIFEST := $(ICON_ASSET_DIR)/theme.conf ICON_METADATA := $(ICON_MANIFEST) $(ICON_ASSET_DIR)/provenance.json $(ICON_ASSET_DIR)/LICENSE -$(EXT2_TEST_IMAGE): $(BT_FIRMWARE_LICENSE) license/libpage-numeric-LICENSE license/libjpeg-turbo-LICENSE license/libwebp-LICENSE license/freetype-LICENSE license/speexdsp-LICENSE license/ffmpeg-LICENSE license/big-buck-bunny-LICENSE license/android-sbc-LICENSE license/unicode-LICENSE license/libmath-LICENSE $(QUICKJS_LICENSE) $(FONT_FIXTURES) $(FONT_PRODUCT) $(ICON_ASSET_DIR) $(ICON_ASSETS) $(ICON_METADATA) $(PAGE_FIXTURES) tools/html_corpus/SOURCES.json $(FRAME_COMPOSITIONS) $(TLS_PUBLIC_ROOTS) tools/gen_ext2_testdata.py $(DEPLOY_APPS) $(DEPLOY_TESTS) $(DEPLOY_LIBS) kernel/test/partition_info.txt etc/husk.rc etc/logd.conf etc/os64get.conf etc/hosts etc/crontab etc/net.conf etc/desktop.conf etc/gclock.conf etc/gterm.conf etc/os64.conf etc/gui.conf etc/menu.conf etc/mouse.conf etc/bootenv.conf etc/sshd.conf etc/vncd.conf etc/fonts.conf etc/icons.conf etc/roam.conf etc/file-associations.conf GNUmakefile +SYSTEM_CONFIG := $(addprefix etc/,husk.rc logd.conf os64get.conf hosts crontab \ + net.conf desktop.conf gclock.conf gterm.conf os64.conf gui.conf menu.conf \ + mouse.conf icons.conf roam.conf file-associations.conf bootenv.conf \ + sshd.conf vncd.conf fonts.conf) +BOOT_MODULES := $(wildcard external/*) +SYSTEM_LICENSES := $(foreach n,libjpeg-turbo libwebp libpage-numeric freetype unicode \ + libmath speexdsp ffmpeg big-buck-bunny android-sbc,$(n).txt:license/$(n)-LICENSE) \ + intel-bluetooth.txt:$(BT_FIRMWARE_LICENSE) quickjs.txt:$(QUICKJS_LICENSE) \ + DejaVu.txt:$(FONT_FIXTURE_DIR)/LICENSE-DejaVu.txt +license_name = $(word 1,$(subst :, ,$(1))) +license_source = $(word 2,$(subst :, ,$(1))) +SYSTEM_LICENSE_SOURCES := $(foreach item,$(SYSTEM_LICENSES),$(call license_source,$(item))) + +# The publisher consumes the same file lists as the images. The FAT boot +# menu and EFI loader have their own maintenance path. Image construction +# also owns its filesystem test scaffold and partition markers. +porter_inputs = $(foreach f,$(2),"$(1)" "$(3)$(notdir $(f))" "$(f)") +PORTER_SYSTEM_INPUTS = $(call porter_inputs,apps,$(DEPLOY_APPS)) \ + $(call porter_inputs,libs,$(DEPLOY_LIBS)) \ + $(call porter_inputs,tests,$(DEPLOY_TESTS)) \ + $(call porter_inputs,tests,$(FONT_FIXTURES),fonts/) \ + $(call porter_inputs,boot,$(DEPLOY_KERNEL) $(BOOT_MODULES)) \ + $(call porter_inputs,config,$(SYSTEM_CONFIG)) \ + $(call porter_inputs,fonts,$(FONT_PRODUCT)) \ + $(call porter_inputs,frames,$(FRAME_COMPOSITIONS)) \ + $(call porter_inputs,pages,$(PAGE_FIXTURES) tools/html_corpus/SOURCES.json) \ + $(call porter_inputs,icons,$(ICON_METADATA) $(ICON_ASSETS)) \ + "certs" "roots.pem" "$(TLS_PUBLIC_ROOTS)" \ + $(foreach item,$(SYSTEM_LICENSES),"licenses" "$(call license_name,$(item))" "$(call license_source,$(item))") +porter_comma := , +porter_system = $(filter system,$(subst $(porter_comma), ,$(PORTER_SCOPES))) + +export PORTER_REPO PORTER_SOURCES PORTER_SOURCES_LOCAL +.PHONY: package porter-package-inputs +package: private export PORTER_SCOPES = $(or $(SCOPES),system) +package: private export PORTER_LABEL := $(if $(filter command,$(origin NAME)),$(value NAME)) +package: private export PORTER_BASELINE = $(BASELINE) +package: private export PORTER_TOOL_CC = $(CC) +package: private export PORTER_TOOL_LD = $(LD) +package: private export PORTER_TOOL_OBJCOPY = $(OBJCOPY) +package: + +@python3 tools/porter_publish.py "$(MAKE)" + +# Only the publisher sets PORTER_INVENTORY, to its own scratch file. +porter-package-inputs: $(if $(porter_system),stage-deploy) + @test -n "$$PORTER_INVENTORY" + @$(if $(porter_system),printf '%s\t%s\t%s\n' $(PORTER_SYSTEM_INPUTS),:) > "$$PORTER_INVENTORY" + +$(EXT2_TEST_IMAGE): $(SYSTEM_LICENSE_SOURCES) $(SYSTEM_CONFIG) $(FONT_FIXTURES) $(FONT_PRODUCT) $(ICON_ASSET_DIR) $(ICON_ASSETS) $(ICON_METADATA) $(PAGE_FIXTURES) tools/html_corpus/SOURCES.json $(FRAME_COMPOSITIONS) $(TLS_PUBLIC_ROOTS) tools/gen_ext2_testdata.py $(DEPLOY_APPS) $(DEPLOY_TESTS) $(DEPLOY_LIBS) kernel/test/partition_info.txt GNUmakefile @mkdir -p "$$(dirname $(EXT2_TEST_IMAGE))" python3 tools/gen_ext2_testdata.py $(EXT2_STAGING) rm -f $(EXT2_TEST_IMAGE) @@ -568,33 +616,15 @@ $(EXT2_TEST_IMAGE): $(BT_FIRMWARE_LICENSE) license/libpage-numeric-LICENSE licen # is writable (ratified 2026-08-07). /etc/husk.rc is the SYSTEM's rc — # /home/husk.rc (the user's, on its own partition) still wins the # search; /fat/husk.rc remains the lifeboat's copy. - printf 'mkdir /bin\nmkdir /tests\nmkdir /lib\nmkdir /etc\nmkdir /tmp\ncd /etc\nwrite etc/husk.rc husk.rc\nwrite etc/logd.conf logd.conf\nwrite etc/os64get.conf os64get.conf\nwrite etc/hosts hosts\nwrite etc/crontab crontab\nwrite etc/net.conf net.conf\nwrite etc/desktop.conf desktop.conf\nwrite etc/gclock.conf gclock.conf\nwrite etc/gterm.conf gterm.conf\nwrite etc/os64.conf os64.conf\nwrite etc/gui.conf gui.conf\nwrite etc/menu.conf menu.conf\nwrite etc/mouse.conf mouse.conf\nwrite etc/icons.conf icons.conf\nwrite etc/roam.conf roam.conf\nwrite etc/file-associations.conf file-associations.conf\nwrite etc/bootenv.conf bootenv.conf\nwrite etc/sshd.conf sshd.conf\nwrite etc/vncd.conf vncd.conf\ncd /bin\n' > $(EXT2_STAGING)/debugfs_bins.cmds + printf 'mkdir /bin\nmkdir /tests\nmkdir /lib\nmkdir /etc\nmkdir /tmp\ncd /etc\n' > $(EXT2_STAGING)/debugfs_bins.cmds + set -e; $(foreach f,$(SYSTEM_CONFIG),printf 'write %s %s\n' "$(f)" "$(notdir $(f))" >> $(EXT2_STAGING)/debugfs_bins.cmds;) + printf 'cd /bin\n' >> $(EXT2_STAGING)/debugfs_bins.cmds # The pinned public roots are system configuration; /home/tls.conf can # select another store through the configuration ladder. printf 'mkdir /etc/certs\nwrite %s /etc/certs/roots.pem\n' "$(TLS_PUBLIC_ROOTS)" >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'mkdir /etc/licenses\nwrite license/libjpeg-turbo-LICENSE /etc/licenses/libjpeg-turbo.txt\nwrite license/libwebp-LICENSE /etc/licenses/libwebp.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'write license/libpage-numeric-LICENSE /etc/licenses/libpage-numeric.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - # The FreeType Licence asks that anything shipping FreeType credit it in - # its documentation. A file on the machine IS this machine's - # documentation, so the credit travels with the library rather than - # living only in a repository nobody has at run time. The shipped file - # is upstream's dual-licence notice followed by the FTL in full, which - # is the option os64 exercises (see libfreetype/UPSTREAM_REVIEW.md). - printf 'write license/freetype-LICENSE /etc/licenses/freetype.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'write license/unicode-LICENSE /etc/licenses/unicode.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'write license/libmath-LICENSE /etc/licenses/libmath.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'write license/speexdsp-LICENSE /etc/licenses/speexdsp.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - # FFmpeg's LGPL notice, and where its source is, travel with libav.so. - printf 'write license/ffmpeg-LICENSE /etc/licenses/ffmpeg.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - # The H.264 test clip in /tests/pages is Big Buck Bunny's (CC-BY 3.0), - # whose attribution travels with it. - printf 'write license/big-buck-bunny-LICENSE /etc/licenses/big-buck-bunny.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - # The kernel carries Android's SBC encoder (kernel/ports/sbc), whose - # Apache 2.0 notice travels with the binary, as speexdsp's does. - printf 'write license/android-sbc-LICENSE /etc/licenses/android-sbc.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'write $(BT_FIRMWARE_LICENSE) /etc/licenses/intel-bluetooth.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'write %s /etc/licenses/quickjs.txt\n' "$(QUICKJS_LICENSE)" >> $(EXT2_STAGING)/debugfs_bins.cmds - printf 'mkdir /etc/fonts\nwrite etc/fonts.conf /etc/fonts.conf\nwrite $(FONT_FIXTURE_DIR)/LICENSE-DejaVu.txt /etc/licenses/DejaVu.txt\n' >> $(EXT2_STAGING)/debugfs_bins.cmds + printf 'mkdir /etc/licenses\n' >> $(EXT2_STAGING)/debugfs_bins.cmds + set -e; $(foreach item,$(SYSTEM_LICENSES),printf 'write %s /etc/licenses/%s\n' "$(call license_source,$(item))" "$(call license_name,$(item))" >> $(EXT2_STAGING)/debugfs_bins.cmds;) + printf 'mkdir /etc/fonts\n' >> $(EXT2_STAGING)/debugfs_bins.cmds $(foreach f,$(FONT_PRODUCT),printf 'write %s /etc/fonts/%s\n' "$(f)" "$(notdir $(f))" >> $(EXT2_STAGING)/debugfs_bins.cmds;) printf 'mkdir /etc/icons\nmkdir /etc/icons/default\n' >> $(EXT2_STAGING)/debugfs_bins.cmds $(foreach f,$(ICON_METADATA),printf 'write %s /etc/icons/default/%s\n' "$(f)" "$(notdir $(f))" >> $(EXT2_STAGING)/debugfs_bins.cmds;) @@ -633,7 +663,7 @@ $(EXT2_TEST_IMAGE): $(BT_FIRMWARE_LICENSE) license/libpage-numeric-LICENSE licen # arrived (2026-08-23) — editing it left the image stale, which presents as "I # changed my wallpaper and nothing happened". Any file the recipe copies belongs # here; that is the whole contract of a prerequisite list. -$(DISK_IMAGE): $(BT_FIRMWARE_LICENSE) license/libpage-numeric-LICENSE license/libjpeg-turbo-LICENSE license/libwebp-LICENSE license/freetype-LICENSE license/speexdsp-LICENSE license/ffmpeg-LICENSE license/big-buck-bunny-LICENSE license/android-sbc-LICENSE license/unicode-LICENSE license/libmath-LICENSE $(QUICKJS_LICENSE) $(DEPLOY_ELFS) $(FONT_FIXTURES) $(FONT_PRODUCT) $(ICON_ASSET_DIR) $(ICON_ASSETS) $(ICON_METADATA) $(PAGE_FIXTURES) tools/html_corpus/SOURCES.json $(FRAME_COMPOSITIONS) kernel/test/partition_info.txt etc/husk.rc etc/desktop.conf etc/gclock.conf etc/gterm.conf etc/os64.conf etc/gui.conf etc/bootenv.conf etc/icons.conf etc/roam.conf etc/file-associations.conf etc/fonts.conf limine-hd.conf $(wildcard external/*) $(EXT2_TEST_IMAGE) GNUmakefile +$(DISK_IMAGE): $(SYSTEM_LICENSE_SOURCES) $(DEPLOY_ELFS) $(FONT_FIXTURES) $(FONT_PRODUCT) $(ICON_ASSET_DIR) $(ICON_ASSETS) $(ICON_METADATA) $(PAGE_FIXTURES) tools/html_corpus/SOURCES.json $(FRAME_COMPOSITIONS) kernel/test/partition_info.txt etc/husk.rc etc/desktop.conf etc/gclock.conf etc/gterm.conf etc/os64.conf etc/gui.conf etc/bootenv.conf etc/icons.conf etc/roam.conf etc/file-associations.conf etc/fonts.conf limine-hd.conf $(BOOT_MODULES) $(EXT2_TEST_IMAGE) GNUmakefile @mkdir -p "$$(dirname $(DISK_IMAGE))" # rm + truncate instead of dd-from-/dev/zero: creates a sparse file, so # rebuilding the image doesn't write $(DISK_SIZE_MB)MB of zeros each time. @@ -710,19 +740,7 @@ $(DISK_IMAGE): $(BT_FIRMWARE_LICENSE) license/libpage-numeric-LICENSE license/li mmd -i $(DISK_IMAGE)@@$(DISK_OFFSET) ::/etc/frames $(foreach f,$(FRAME_COMPOSITIONS),mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) $(f) ::/etc/frames/$(notdir $(f));) mmd -i $(DISK_IMAGE)@@$(DISK_OFFSET) ::/etc/licenses - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) $(FONT_FIXTURE_DIR)/LICENSE-DejaVu.txt ::/etc/licenses/DejaVu.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/libjpeg-turbo-LICENSE ::/etc/licenses/libjpeg-turbo.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/libwebp-LICENSE ::/etc/licenses/libwebp.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/libpage-numeric-LICENSE ::/etc/licenses/libpage-numeric.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/freetype-LICENSE ::/etc/licenses/freetype.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/unicode-LICENSE ::/etc/licenses/unicode.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/libmath-LICENSE ::/etc/licenses/libmath.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/speexdsp-LICENSE ::/etc/licenses/speexdsp.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/ffmpeg-LICENSE ::/etc/licenses/ffmpeg.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/big-buck-bunny-LICENSE ::/etc/licenses/big-buck-bunny.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) license/android-sbc-LICENSE ::/etc/licenses/android-sbc.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) $(BT_FIRMWARE_LICENSE) ::/etc/licenses/intel-bluetooth.txt - mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) $(QUICKJS_LICENSE) ::/etc/licenses/quickjs.txt + set -e; $(foreach item,$(SYSTEM_LICENSES),mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) "$(call license_source,$(item))" ::/etc/licenses/$(call license_name,$(item));) mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) etc/desktop.conf ::/etc/desktop.conf mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) etc/gclock.conf ::/etc/gclock.conf mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) etc/gterm.conf ::/etc/gterm.conf @@ -755,7 +773,7 @@ $(DISK_IMAGE): $(BT_FIRMWARE_LICENSE) license/libpage-numeric-LICENSE license/li -@mmd -i $(DISK_IMAGE)@@$(DISK_OFFSET) ::/EFI > /dev/null 2>&1 -@mmd -i $(DISK_IMAGE)@@$(DISK_OFFSET) ::/EFI/BOOT > /dev/null 2>&1 mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) $(DEPLOY_KERNEL) ::/boot/os64_kernel - $(foreach e,$(wildcard external/*),\ + $(foreach e,$(BOOT_MODULES),\ mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) $(e) ::/boot/$(notdir $(e));) mcopy -o -i $(DISK_IMAGE)@@$(DISK_OFFSET) limine-hd.conf ::/boot/limine/limine.conf # Limine's own EFI app rides too — the lifeboat is a complete BOOT @@ -909,8 +927,8 @@ $(IMAGE_NAME).iso: $(BT_FIRMWARE_LICENSE) limine/limine $(DEPLOY_KERNEL) $(DISK_ # (see /RAMDisk Boot in limine.conf). Copied after disk-populate so the # module always carries the freshly built test binaries. cp $(DISK_IMAGE) iso_root/boot/os64_disk.img - @cp external/* iso_root/boot/ - @cp external/* iso_root/ + @cp $(BOOT_MODULES) iso_root/boot/ + @cp $(BOOT_MODULES) iso_root/ @mkdir -p iso_root/boot/limine @cp limine.conf limine/limine-bios.sys limine/limine-bios-cd.bin limine/limine-uefi-cd.bin iso_root/boot/limine/ @mkdir -p iso_root/EFI/BOOT diff --git a/README.md b/README.md index c86f13f69..78dfc82a1 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,9 @@ The images carry the full kernel ELF to preserve the boot layout used by Limine on UEFI. Kernel DWARF paths are relative to the repository. Run GDB from the checkout root for source lookup. +`make package` publishes an immutable Porter snapshot of the installable files. +[Porter publishing and server setup](docs/design/pending/PORTER_PUBLISHING.md) + ### Running ```bash diff --git a/docs/design/pending/PORTER_PUBLISHING.md b/docs/design/pending/PORTER_PUBLISHING.md new file mode 100644 index 000000000..60c9ccb12 --- /dev/null +++ b/docs/design/pending/PORTER_PUBLISHING.md @@ -0,0 +1,124 @@ +# Publishing Porter packages + +Porter publishes complete installable file sets from a build checkout. Each +publication can name one system target and any number of independently managed +collections. The guest preview and install rules are described in the design. +[Porter design](INSTALLER.md) + +## Publish a build + +```sh +make package +make package NAME="Audio preview" +make package BASELINE=1 NAME="November userland baseline" +``` + +Run the publisher from the Linux or WSL checkout with Python 3.10 or later. +The default repository is a sibling of the primary checkout, named +`-porter`. Set `PORTER_REPO=/absolute/path` to share another repository +outside the checkout with Windows Python. The publishing filesystem must +support advisory locks, atomic same-directory rename and directory sync. +Build the normal images through `make` as usual. Publication starts through +the explicit `package` target. + +With no command-line `NAME`, the label uses the branch and the local date and +time with its UTC offset. `BASELINE=1` marks the publication as a candidate +for baseline adoption. The label and baseline flag live in the publication +record. Manifests and objects are addressed by their contents, and each +publication receives its own ID even when the label and contents repeat. + +The system scope uses Make's staged apps, aliases, libraries, test fixtures +and full kernel, plus the boot modules, system config, licenses, trust roots, +fonts, frames, pages and icons selected by the image build. It declares the +exact kernel ELF SHA-256 as its kernel contract. The boot menu, EFI loader, +filesystem test scaffolding, partition markers and user data have their own +lifecycles. + +## Add recursive collections + +The default build-side source file is `porter-sources.conf` in the checkout. +`PORTER_SOURCES` selects an explicit file, and `PORTER_SOURCES_LOCAL` adds a +local overlay. An explicitly named file and the roots of selected collections +must be readable. Relative directory names start at the publishing checkout. + +```ini +[sources] +fonts += extras/system fonts + +[sources recordings] +sounds += /mnt/media/Recordings + +[sources themes] +themepacks += local/Theme Packs +``` + +```sh +make package SCOPES=recordings NAME="Field recordings" +make package SCOPES=system,themes NAME="Desktop preview" +``` + +A source root contributes its contents, retaining relative subdirectories and +empty directories. A registered nested root owns its subtree. Its parent skips +that subtree even when the nested root's scope is outside the publication. +Files and directories with equal lot, relative path, kind and content +coalesce. Other definitions at that key report both inputs. +Links, Windows reparse points and special files are excluded from collection. +An empty scanned root still declares its lot. The source paths and overlays +remain on the publishing machine. + +Each scope allows up to 16,384 entries. Names in `LOT/PATH` must fit the Os64 +ustar encoding and its 255-byte path limit. File sizes use the ustar limit of +8,589,934,591 bytes. These are transport limits. The guest's destination +filesystem can impose further limits. + +## Serve from Windows + +Run the updated `tools/os64serve.py` next to `tools/porter_store.py` using +Windows Python. Add `--porter-repo` to the existing valet invocation and +supply the Windows-visible path to the publication repository. + +```powershell +python.exe '\\wsl$\\home\\src\os64\tools\os64serve.py' --porter-repo '\\wsl$\\home\\src\os64-porter' 'C:\Os64\bin' +``` + +A repository-only invocation serves Porter. Existing directory arguments +continue to serve legacy `GET` and `LIST` on the same port. Point the server at +the repository itself, so it can see later atomic publications without a +restart. [Legacy server setup](../completed/OS64GET.md#running-os64serve) + +## Porter v1 wire format + +Each request uses its own TCP connection and starts with an ASCII line ending +in LF. These operations use the existing trusted-LAN listener. + +| Request | Successful response | +| --- | --- | +| `CATALOG` | `OK\n`, then one canonical publication JSON object per line, then `.\n` | +| `MANIFEST ID` | `OK LENGTH\n`, then exactly `LENGTH` canonical JSON bytes | +| `ARCHIVE ID` | `OK LENGTH\n`, then exactly `LENGTH` bytes of a standalone tar.gz | +| `ARCHIVE ID LENGTH` followed by a JSON array | Same archive framing for the selected manifest entries | + +An `ID` is a manifest's lowercase hexadecimal SHA-256. Canonical JSON uses ASCII +escapes, sorted object keys, compact separators and zero trailing bytes. A +selection is a compact JSON array of strictly increasing zero-based entry +indices, at most 128 KiB, with exactly the declared byte length. An empty +selection yields an empty archive. The server sends selected entries in +manifest order. Include a directory's index when it is part of the selection. + +An unavailable target or malformed request returns `NO reason\n`. A stream +failure after the success header ends the connection without completing the +response. A receiver checks the declared length or catalog terminator, then +validates the archive and manifest before using the bytes. + +A manifest records the version, scope, kernel contract, selected lots and +entries sorted by lot and relative path. A file entry has its uncompressed +length and SHA-256. A directory entry has its kind and path. Catalog records +map names and source provenance to manifest IDs. The catalog streams metadata +directly from the completed publication records. + +The repository stores one gzip member per distinct file, containing its bytes +and zero padding to a 512-byte boundary. Serving a tar.gz combines normalized +ustar header members, stored data members and a two-block terminator. The +server verifies members while streaming in bounded chunks. The repository +keeps the objects and manifests reachable from its catalog, so completed +publications remain available when their input files or checkouts are removed. diff --git a/docs/design/pending/PORTER_TRACKER.csv b/docs/design/pending/PORTER_TRACKER.csv index 3c9babff6..e5ca23c37 100644 --- a/docs/design/pending/PORTER_TRACKER.csv +++ b/docs/design/pending/PORTER_TRACKER.csv @@ -7,7 +7,14 @@ P.1.4,Compare SHA-256 inventories of all installable ELF and data files,P.1.2 P. P.1.5,Boot the normal image and lifeboat and check guest trace names and host GDB symbols,P.1.3,done,#733,BIOS ext2 and direct UEFI FAT boots passed with named traces and live host GDB source lookup. P.1.6,Keep the full kernel ELF and normalize its DWARF paths,P.1.3,done,#733,ADDED 2026-11-24: stripping the kernel exposed a write-protection fault during UEFI boot. The large-page handoff is tracked in DEBTS.md. -P.2,Publish immutable packages and serve them from Windows,P.1,todo,,Verify full and selective compressed transfers and concurrent publication. +P.2,Publish immutable packages and serve them from Windows,P.1,done,#734,Concurrent publication and full and selective archives verified with GNU tools and Os64. Native Windows loopback passed 12 repetitions. +P.2.1,Expose complete Make-selected system inputs and explicit package publication,P.1,done,#734,The system manifest matched 608 ext2 files and five FAT and ISO boot files. +P.2.2,Collect recursive source lots and independent scopes,P.2.1,done,#734,"Verified recursive roots, nested ownership, duplicate paths, conflicts and source changes." +P.2.3,Publish canonical manifests and verified immutable gzip objects atomically,P.2.2,done,#734,"Verified concurrent publications, deduplication and distinct records for repeated labels." +P.2.4,Serve catalogs and manifests and stream full or selective archives,P.2.3,done,#734,Verified full and selective archives and legacy GET and LIST on native Windows loopback. +P.2.5,Run host and Os64 archive compatibility and failure tests,P.2.4,done,#734,GNU and Os64 archive proofs passed including 64 MiB media and corrupt or truncated inputs. Windows loopback passed. +P.2.6,Resolve the intermittent Windows archive interruption,P.2.4,done,#734,ADDED 2026-11-24: the native server refused an unchanged object. Path and handle stats now compare timestamps within each API. + P.3,Preview installs from the Porter CLI,P.2,todo,,Distinguish known downgrades from local edits and check resolved destination collisions. P.4,Implement checked storage barriers and ext2 install and undo,P.3,todo,,Verify interrupted transactions and offline recovery with a disposable disk. P.5,Update FAT and kernel files and prove bootable rescue,P.4,todo,,Boot the known-good rescue runtime and exercise failure and reboot boundaries. diff --git a/tools/os64serve.py b/tools/os64serve.py index 7b18b3601..78b578bc3 100644 --- a/tools/os64serve.py +++ b/tools/os64serve.py @@ -5,11 +5,12 @@ python3 tools/os64serve.py userland/bin userland/bin/tests=tests userland/bin/pages=pages userland/bin/fonts=fonts kernel/bin=kernelbin etc frames=frames assets/icons/default=icons Options: - [PATH|PATH=LOT ...] [--port 6464] [--bind 0.0.0.0] + [PATH|PATH=LOT ...] [--porter-repo PATH] [--port 6464] [--bind 0.0.0.0] Directories are searched in order, first usable file wins, without recursion. LOT labels describe the source; the client's os64get.conf chooses destinations. -With no directory arguments the server offers its current directory. +With no directory or repository arguments the server offers its current directory. +--porter-repo also serves immutable Porter targets. See PORTER_PUBLISHING.md. The current os64get client uses port 6464 with no override. See OS64GET.md for the installer workflow, configuration, replacement backups, @@ -20,11 +21,14 @@ import argparse import os +from pathlib import Path import socket import stat import sys import zlib +from porter_store import serve_porter + CHUNK = 65536 @@ -98,7 +102,7 @@ def read_served_file_multi(directories, name): return None -def serve_one(conn, addr, directories): +def serve_one(conn, addr, directories, porter_repo=None): conn.settimeout(30) try: # Read the request line one byte at a time. A stream has no message @@ -117,6 +121,8 @@ def serve_one(conn, addr, directories): return line = request.decode("utf-8", "replace").strip() + if serve_porter(porter_repo, line, conn.recv, conn.sendall): + return # LIST - "what have you got?" (2026-08-22). The day libos64 became a # shared object the payload became 66 files, and one invocation per @@ -203,8 +209,8 @@ def serve_one(conn, addr, directories): except socket.timeout: print(f" {addr[0]}: timed out") - except (ConnectionResetError, BrokenPipeError): - print(f" {addr[0]}: connection reset") + except OSError as exc: + print(f" {addr[0]}: connection failed: {exc}") finally: conn.close() @@ -244,6 +250,8 @@ def main(): ap.add_argument("--port", type=int, default=6464) ap.add_argument("--bind", default="0.0.0.0", help="address to listen on (default: everything)") + ap.add_argument("--porter-repo", type=Path, + help="published Porter repository, including a Windows UNC path") args = ap.parse_args() # NO DIRECTORY NAMED MEANS THE CURRENT ONE, and that has to announce @@ -252,9 +260,9 @@ def main(): # multi-line command pasted into cmd.exe runs its first line alone — and # the result is a valet quietly offering your home directory to anything # that dials in. An `os64get -a` against that installs it. Loud, then. - defaulted = not args.directories + defaulted = not args.directories and args.porter_repo is None try: - directories = [split_lot(d) for d in (args.directories or ["."])] + directories = [split_lot(d) for d in (["."] if defaulted else args.directories)] except ValueError as exc: print(f"os64serve: {exc}", file=sys.stderr) return 2 @@ -268,6 +276,14 @@ def main(): if not os.path.isdir(directory): print(f"os64serve: {directory} is not a directory", file=sys.stderr) return 2 + porter_repo = args.porter_repo + if porter_repo is not None: + porter_repo = porter_repo.expanduser().absolute() + for kind in ("publications", "manifests", "objects"): + if not (porter_repo / kind).is_dir(): + print(f"os64serve: missing Porter repository directory: {porter_repo / kind}", + file=sys.stderr) + return 2 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # A second os64serve on the same port must refuse to start: two of them @@ -286,7 +302,9 @@ def main(): s.bind((args.bind, args.port)) s.listen(4) - print(f"os64serve: serving on {args.bind}:{args.port}, first hit wins:") + print(f"os64serve: serving on {args.bind}:{s.getsockname()[1]}", flush=True) + if porter_repo is not None: + print(f" {porter_repo} [Porter repository]") for directory, lot in directories: print(f" {directory}" + (f" [lot {lot}]" if lot else "")) @@ -338,7 +356,7 @@ def main(): continue conn.settimeout(None) # an accepted socket inherits the listener's # timeout; serve_one sets the one it wants - serve_one(conn, addr, directories) + serve_one(conn, addr, directories, porter_repo) except KeyboardInterrupt: print("\nos64serve: stopped.") finally: diff --git a/tools/porter_publish.py b/tools/porter_publish.py new file mode 100644 index 000000000..20da1fc34 --- /dev/null +++ b/tools/porter_publish.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +"""Build the selected scopes and publish them to a local Porter repository.""" + +from contextlib import contextmanager +from dataclasses import dataclass +from datetime import datetime +import fcntl +import gzip +import hashlib +import os +from pathlib import Path, PurePosixPath +import re +import shlex +import stat +import subprocess +import sys +import tempfile +from uuid import uuid4 + +from porter_store import ( + CHUNK, LOT, MAX_ENTRIES, MAX_FILE, MAX_JSON, PorterError, archive_header, + canonical, check_manifest, check_member, fingerprint, is_link, object_path, + padding, read_metadata, regular_info, regular_stream, +) + + +BASE_LOTS = {"apps", "libs", "tests", "boot", "config", "fonts", "frames", + "pages", "icons", "certs", "licenses"} +SECTION = re.compile(r"\[sources(?: ([a-z][a-z0-9_-]{0,30}))?\]", re.ASCII) + + +@dataclass(frozen=True) +class Source: + scope: str + lot: str + root: Path + + +@dataclass(frozen=True) +class Input: + scope: str + lot: str + path: str + source: Path + info: os.stat_result + + +def absolute(root, path): + return Path(os.path.abspath(root / Path(path).expanduser())) + + +def read_sources(root, repo, files): + sources = [] + documents = {} + owners = {} + for path, required in files: + try: + raw = read_metadata(path) + except FileNotFoundError: + if required or path.is_symlink(): + raise + documents[path] = None + continue + documents[path] = raw + scope = None + for number, line in enumerate(raw.decode("utf-8").splitlines(), 1): + line = line.strip() + if not line or line.startswith(("#", ";")): + continue + section = SECTION.fullmatch(line) + if section: + scope = section[1] or "system" + continue + key, sign, value = line.partition("+=") + lot, name = key.strip(), value.strip() + if not scope or not sign or not LOT.fullmatch(lot) or not name: + raise PorterError(f"{path}:{number}: expected a source section or lot += directory") + folder = absolute(root, name) + if folder.is_relative_to(repo) or repo.is_relative_to(folder): + raise PorterError(f"source and package repository overlap: {folder}") + origin = f"{path}:{number}" + record = Source(scope, lot, folder) + if folder in owners: + previous, previous_origin = owners[folder] + if previous != record: + raise PorterError(f"conflicting registrations for {folder}: {previous_origin} and {origin}") + continue + owners[folder] = record, origin + sources.append(record) + return sources, documents + + +def directory_info(path): + info = path.lstat() + if is_link(info) or not stat.S_ISDIR(info.st_mode): + raise PorterError(f"expected a directory without links: {path}") + return info + + +def require_unlinked_parents(path): + for parent in reversed(path.parents): + directory_info(parent) + + +def collect(selected, builtins, sources, report): + inputs = [] + scanned = {} + roots = {source.root for source in sources} + for path, lot, name in builtins: + require_unlinked_parents(path) + inputs.append(Input("system", lot, name, path, regular_info(path))) + for source in sources: + if source.scope not in selected: + continue + require_unlinked_parents(source.root) + directory_info(source.root) + queue = [source.root] + while queue: + folder = queue.pop() + scanned[folder] = fingerprint(directory_info(folder)) + with os.scandir(folder) as listing: + for item in sorted(listing, key=lambda entry: entry.name): + child = Path(item.path) + if child in roots: + continue + before = item.stat(follow_symlinks=False) + rel = child.relative_to(source.root).as_posix() + if is_link(before) or not (stat.S_ISDIR(before.st_mode) or stat.S_ISREG(before.st_mode)): + if report: + print(f"porter: excluded link or special file: {child}", file=sys.stderr) + continue + inputs.append(Input(source.scope, source.lot, rel, child, before)) + if stat.S_ISDIR(before.st_mode): + queue.append(child) + return inputs, scanned + + +def input_snapshot(inputs, directories): + return ({(i.scope, i.lot, i.path, i.source): fingerprint(i.info) for i in inputs}, + directories) + + +def built_in_inputs(root, inventory): + inputs = [] + for line in inventory.read_text(encoding="utf-8").splitlines(): + fields = line.split("\t") + if len(fields) != 3 or not LOT.fullmatch(fields[0]): + raise PorterError("invalid Make inventory") + lot, name, src = fields + inputs.append((absolute(root, src), lot, name)) + return inputs + + +@contextmanager +def lock(path): + with path.open("ab") as stream: + fcntl.flock(stream, fcntl.LOCK_EX) + yield + + +def sync_dir(path): + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def put_metadata(path, raw): + if len(raw) > MAX_JSON: + raise PorterError(f"metadata exceeds {MAX_JSON} bytes") + if path.exists(): + if read_metadata(path) != raw: + raise PorterError(f"immutable record differs: {path}") + return + with tempfile.NamedTemporaryFile(dir=path.parent, prefix=".incoming-", delete=False) as out: + temp = Path(out.name) + try: + out.write(raw) + out.flush() + os.fsync(out.fileno()) + out.close() + os.replace(temp, path) + finally: + temp.unlink(missing_ok=True) + + +def read_source(item, member=None): + size = item.info.st_size + hasher = hashlib.sha256() + total = 0 + require_unlinked_parents(item.source) + with regular_stream(item.source, item.info) as source: + while chunk := source.read(CHUNK): + total += len(chunk) + if total > size: + raise PorterError(f"file grew while reading: {item.source}") + hasher.update(chunk) + if member is not None: + member.write(chunk) + if total != size: + raise PorterError(f"file size changed: {item.source}") + return hasher.hexdigest() + + +def capture(repo, item, verified): + size = item.info.st_size + if size > MAX_FILE: + raise PorterError(f"file is too large for ustar: {item.source}") + digest = read_source(item) + if digest in verified: + if verified[digest] != size: + raise PorterError("conflicting object sizes") + return digest + + dest = object_path(repo, digest) + if dest.exists(): + with regular_stream(dest) as existing: + check_member(existing, digest, size) + else: + with tempfile.NamedTemporaryFile(dir=dest.parent, prefix=".incoming-", delete=False) as out: + temp = Path(out.name) + try: + with gzip.GzipFile(filename="", fileobj=out, mode="wb", mtime=0, compresslevel=6) as member: + if read_source(item, member) != digest: + raise PorterError(f"file contents changed: {item.source}") + member.write(bytes(padding(size))) + out.flush() + os.fsync(out.fileno()) + out.close() + with regular_stream(temp) as check: + check_member(check, digest, size) + os.replace(temp, dest) + finally: + temp.unlink(missing_ok=True) + verified[digest] = size + return digest + + +def add_entry(entries, entry, source): + key = entry["lot"], entry["path"] + if key in entries: + previous, previous_source = entries[key] + if previous != entry: + raise PorterError(f"conflicting {key[0]}/{key[1]}: {previous_source} and {source}") + return + if len(entries) >= MAX_ENTRIES: + raise PorterError(f"too many entries in scope (maximum {MAX_ENTRIES})") + archive_header(entry) + entries[key] = entry, source + + +def manifests(repo, selected, inputs, sources): + records = {scope: {} for scope in selected} + lots = {scope: set() for scope in selected} + if "system" in selected: + lots["system"].update(BASE_LOTS) + for source in sources: + if source.scope in selected: + lots[source.scope].add(source.lot) + verified = {} + captured = {} + for item in inputs: + entries = records[item.scope] + lots[item.scope].add(item.lot) + entry = {"lot": item.lot, "path": item.path, "kind": "dir"} + if stat.S_ISREG(item.info.st_mode): + entry.update(kind="file", size=item.info.st_size) + # Validate the original name before PurePosixPath can normalize it. + archive_header(entry) + for parent in reversed(PurePosixPath(item.path).parents): + if parent != PurePosixPath("."): + add_entry(entries, {"lot": item.lot, "path": parent.as_posix(), "kind": "dir"}, + item.source) + if entry["kind"] == "file": + if item.source not in captured: + captured[item.source] = capture(repo, item, verified) + entry["sha256"] = captured[item.source] + add_entry(entries, entry, item.source) + for scope, entries in records.items(): + kernel = None + if scope == "system": + kernel_entry = entries.get(("boot", "os64_kernel")) + if kernel_entry is None or kernel_entry[0]["kind"] != "file": + raise PorterError("Make inventory is missing the system kernel") + kernel = {"elf_sha256": kernel_entry[0]["sha256"]} + manifest = {"version": 1, "scope": scope, "kernel": kernel, "lots": sorted(lots[scope]), + "entries": [entries[key][0] for key in sorted(entries)]} + check_manifest(manifest) + yield scope, manifest + + +def git(root, *args): + return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip() + + +def provenance(root): + revision = git(root, "rev-parse", "HEAD") + branch = git(root, "rev-parse", "--abbrev-ref", "HEAD") + dirty = git(root, "status", "--porcelain", "--untracked-files=normal") + return revision, branch, dirty + + +def toolchain(): + defaults = {"cc": "x86_64-elf-gcc", "ld": "x86_64-elf-ld", + "objcopy": "x86_64-elf-objcopy", "nasm": "nasm"} + result = {} + for key, default in defaults.items(): + command = shlex.split(os.environ.get(f"PORTER_TOOL_{key.upper()}") or default) + if key == "cc" and len(command) > 1 and Path(command[0]).name == "ccache": + command = command[1:] + result[key] = subprocess.check_output(command + ["--version"], text=True).splitlines()[0] + return result + + +def publish_targets(root, repo, selected, builtins, source_files, build): + inputs, folders = collect(selected, builtins, build[0], True) + snapshot = input_snapshot(inputs, folders) + targets = {} + for scope, manifest in manifests(repo, selected, inputs, build[0]): + raw = canonical(manifest) + digest = hashlib.sha256(raw).hexdigest() + put_metadata(repo / "manifests" / (digest + ".json"), raw) + targets[scope] = digest + sync_dir(repo / "objects") + sync_dir(repo / "manifests") + if (build != read_sources(root, repo, source_files) + or snapshot != input_snapshot(*collect(selected, builtins, build[0], False))): + raise PorterError("source selection or contents changed during publication") + return targets + + +def main(): + # Make runs recursive recipes even when it is only printing, querying or + # touching targets. These modes must not publish or start a sub-build. + flags = os.environ.get("MAKEFLAGS", "").split() + if flags and not flags[0].startswith("-") and set(flags[0]).intersection("nqt"): + return + root = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) + common = Path(git(root, "rev-parse", "--path-format=absolute", "--git-common-dir")).parent + default_repo = common.with_name(common.name + "-porter") + repo = absolute(root, os.environ.get("PORTER_REPO") or default_repo).resolve() + if repo.is_relative_to(root) or repo.is_relative_to(common): + raise PorterError("the package repository must be outside the checkout") + selected = os.environ.get("PORTER_SCOPES", "system").split(",") + if any(not LOT.fullmatch(scope) for scope in selected) or len(set(selected)) != len(selected): + raise PorterError("SCOPES must be a comma-separated list of distinct scope names") + baseline = os.environ.get("PORTER_BASELINE", "") + if baseline not in ("", "0", "1"): + raise PorterError("BASELINE must be 0 or 1") + name = os.environ.get("PORTER_LABEL", "") + if len(name.encode("utf-8")) > 256 or any(ord(ch) < 32 or ord(ch) == 127 for ch in name): + raise PorterError("NAME must be at most 256 UTF-8 bytes with no control characters") + source_files = [(absolute(root, os.environ.get("PORTER_SOURCES") or "porter-sources.conf"), + bool(os.environ.get("PORTER_SOURCES")))] + overlay = os.environ.get("PORTER_SOURCES_LOCAL") + if overlay: + source_files.append((absolute(root, overlay), True)) + + for directory in ("objects", "manifests", "publications"): + path = repo / directory + path.mkdir(parents=True, exist_ok=True) + directory_info(path) + sync_dir(repo) + local = root / "disk" + local.mkdir(exist_ok=True) + with lock(local / ".porter-build.lock"), tempfile.TemporaryDirectory() as scratch: + inventory = Path(scratch) / "inventory" + build = read_sources(root, repo, source_files) + for scope in selected: + if scope != "system" and not any(source.scope == scope for source in build[0]): + raise PorterError(f"no sources configured for scope {scope!r}") + before = provenance(root) + builtins = [] + tools = {} + if "system" in selected: + environment = dict(os.environ, PORTER_INVENTORY=str(inventory)) + subprocess.run([sys.argv[1], "porter-package-inputs"], cwd=root, + env=environment, check=True, close_fds=False) + builtins = built_in_inputs(root, inventory) + tools = toolchain() + with lock(repo / ".publish.lock"): + targets = publish_targets(root, repo, selected, builtins, source_files, build) + if provenance(root) != before: + raise PorterError("checkout changed during publication") + revision, branch, dirty = before + now = datetime.now().astimezone().isoformat(timespec="seconds") + identifier = uuid4().hex + label = revision[:12] if branch == "HEAD" else branch + # Host paths stay private. The rule summary describes how the + # inputs were selected without exporting the source configs. + record = { + "version": 1, "id": identifier, "name": name or f"{label} {now}", + "baseline": baseline == "1", "published_at": now, + "revision": revision, "branch": branch, "dirty": bool(dirty), "toolchain": tools, + "input_rules": {"make": "system" in selected, "recursive": True, + "nested_sources_own_subtrees": True, + "sources": [ + {"scope": source.scope, "lot": source.lot, + "location": "checkout" if source.root.is_relative_to(root) else "external"} + for source in build[0] if source.scope in selected + ]}, + "targets": targets, + } + put_metadata(repo / "publications" / (identifier + ".json"), canonical(record)) + sync_dir(repo / "publications") + print(f"porter: published {identifier} " + " ".join(f"{s}={h}" for s, h in targets.items())) + + +if __name__ == "__main__": + try: + main() + except (PorterError, OSError, UnicodeError, subprocess.CalledProcessError) as error: + sys.exit(f"porter: {error}") diff --git a/tools/porter_store.py b/tools/porter_store.py new file mode 100644 index 000000000..828477810 --- /dev/null +++ b/tools/porter_store.py @@ -0,0 +1,328 @@ +"""Porter v1 repository formats and streaming archive service.""" + +from contextlib import contextmanager +import gzip +import hashlib +import io +import json +import os +from pathlib import Path +import re +import stat +import tarfile +import zlib + + +CHUNK = 64 * 1024 +BLOCK = 512 +MAX_FILE = 8**11 - 1 # ustar's eleven octal size digits +MAX_ENTRIES = 16_384 +MAX_JSON = 16 * 1024 * 1024 +MAX_SELECTION = 128 * 1024 +ID = re.compile(r"[0-9a-f]{64}", re.ASCII) +LOT = re.compile(r"[a-z][a-z0-9_-]{0,30}", re.ASCII) +PUBLICATION_ID = re.compile(r"[0-9a-f]{32}", re.ASCII) + + +class PorterError(ValueError): + pass + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), + ensure_ascii=True, allow_nan=False).encode("ascii") + + +def parse_json(raw): + try: + value = json.loads(raw) + if canonical(value) != raw: + raise PorterError("JSON is not canonical") + return value + except (ValueError, RecursionError, UnicodeError) as exc: + raise PorterError("invalid canonical JSON") from exc + + +def is_link(info): + return stat.S_ISLNK(info.st_mode) or bool( + getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT + ) + + +def fingerprint(info): + return info.st_dev, info.st_ino, info.st_mode, info.st_size, info.st_mtime_ns, info.st_ctime_ns + + +def regular_info(path): + info = path.lstat() + if is_link(info) or not stat.S_ISREG(info.st_mode): + raise PorterError(f"expected a regular file: {path}") + return info + + +def open_matches_path(named, opened): + if os.name == "nt": + # Windows path and handle stat can report different ctime for the + # same file. Compare metadata for changes within each stat API. + return (os.path.samestat(named, opened) + and stat.S_IFMT(named.st_mode) == stat.S_IFMT(opened.st_mode) + and named.st_size == opened.st_size) + return fingerprint(named) == fingerprint(opened) + + +@contextmanager +def regular_stream(path, expected=None): + before = regular_info(path) + if expected is not None and fingerprint(before) != fingerprint(expected): + raise PorterError(f"file changed: {path}") + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + flags |= getattr(os, "O_NONBLOCK", 0) + with os.fdopen(os.open(path, flags), "rb") as stream: + opened = os.fstat(stream.fileno()) + if is_link(opened) or not open_matches_path(before, opened): + raise PorterError(f"file changed while opening: {path}") + yield stream + if (fingerprint(os.fstat(stream.fileno())) != fingerprint(opened) + or fingerprint(regular_info(path)) != fingerprint(before)): + raise PorterError(f"file changed while reading: {path}") + + +def read_metadata(path): + with regular_stream(path) as stream: + data = stream.read(MAX_JSON + 1) + if len(data) > MAX_JSON: + raise PorterError(f"metadata exceeds {MAX_JSON} bytes: {path}") + return data + + +def object_path(repo, digest): + if not isinstance(digest, str) or not ID.fullmatch(digest): + raise PorterError("invalid content ID") + return repo / "objects" / (digest + ".gz") + + +def gzip_member(data): + output = io.BytesIO() + with gzip.GzipFile(filename="", fileobj=output, mode="wb", mtime=0) as member: + member.write(data) + return output.getvalue() + + +def padding(size): + return (-size) % BLOCK + + +def archive_header(entry): + name = f'{entry["lot"]}/{entry["path"]}' + relative = entry["path"] + if (any(part in ("", ".", "..") for part in relative.split("/")) + or any(ord(ch) < 32 or ord(ch) == 127 or ch in "\\:" for ch in relative)): + raise PorterError(f"unsafe archive path: {name!r}") + item = tarfile.TarInfo(name) + if entry["kind"] == "dir": + item.type = tarfile.DIRTYPE + item.mode = 0o755 + else: + item.size = entry["size"] + item.mode = 0o755 if entry["lot"] in ("apps", "tests") and "/" not in relative else 0o644 + try: + # The directory slash added by TarInfo also has to fit Os64's buffer. + if len(name.encode("utf-8")) + (item.type == tarfile.DIRTYPE) >= 256: + raise ValueError("Os64 tar path limit") + return item.tobuf(tarfile.USTAR_FORMAT, "utf-8", "strict") + except (ValueError, UnicodeError) as exc: + raise PorterError(f"path or size is outside Os64 ustar limits: {name!r}") from exc + + +def check_manifest(manifest): + if (not isinstance(manifest, dict) + or set(manifest) != {"version", "scope", "kernel", "lots", "entries"} + or type(manifest["version"]) is not int or manifest["version"] != 1): + raise PorterError("invalid manifest format") + scope, lots, entries = manifest["scope"], manifest["lots"], manifest["entries"] + if (not isinstance(scope, str) or not LOT.fullmatch(scope) + or not isinstance(lots, list) or not lots + or any(not isinstance(lot, str) or not LOT.fullmatch(lot) for lot in lots) + or lots != sorted(set(lots)) + or not isinstance(entries, list) or len(entries) > MAX_ENTRIES): + raise PorterError("invalid manifest scope, lots or entry count") + kernel = manifest["kernel"] + if scope == "system": + if (not isinstance(kernel, dict) or set(kernel) != {"elf_sha256"} + or not isinstance(kernel["elf_sha256"], str) or not ID.fullmatch(kernel["elf_sha256"])): + raise PorterError("invalid system kernel contract") + elif kernel is not None: + raise PorterError("independent scopes cannot declare a kernel") + known = {} + sizes = {} + previous = ("", "") + for entry in entries: + if not isinstance(entry, dict) or not {"lot", "path", "kind"} <= entry.keys(): + raise PorterError("invalid manifest entry") + lot, path, kind = entry["lot"], entry["path"], entry["kind"] + if not isinstance(lot, str) or lot not in lots or not isinstance(path, str): + raise PorterError("invalid manifest path or lot") + if (lot, path) <= previous: + raise PorterError("manifest entries are duplicated or unsorted") + previous = (lot, path) + parent, sep, _ = path.rpartition("/") + if sep and known.get((lot, parent)) != "dir": + raise PorterError(f"missing directory for {lot}/{path}") + if kind == "file": + if (set(entry) != {"lot", "path", "kind", "size", "sha256"} + or type(entry["size"]) is not int or not 0 <= entry["size"] <= MAX_FILE + or not isinstance(entry["sha256"], str) or not ID.fullmatch(entry["sha256"])): + raise PorterError("invalid manifest file") + if sizes.setdefault(entry["sha256"], entry["size"]) != entry["size"]: + raise PorterError("conflicting content lengths") + elif kind != "dir" or set(entry) != {"lot", "path", "kind"}: + raise PorterError("invalid manifest directory") + archive_header(entry) + known[(lot, path)] = kind + if scope == "system" and not any( + e["lot"] == "boot" and e["path"] == "os64_kernel" and e.get("sha256") == kernel["elf_sha256"] + for e in entries + ): + raise PorterError("system manifest does not contain its kernel") + + +def load_manifest(repo, digest): + if not isinstance(digest, str) or not ID.fullmatch(digest): + raise PorterError("invalid target ID") + raw = read_metadata(repo / "manifests" / (digest + ".json")) + if hashlib.sha256(raw).hexdigest() != digest: + raise PorterError("manifest digest mismatch") + value = parse_json(raw) + check_manifest(value) + return raw, value + + +def check_member(stream, digest, size, send=None, wire_size=None): + """Verify one gzip member, including its zero tar padding and trailer.""" + decoder = zlib.decompressobj(31) + hasher = hashlib.sha256() + decoded = compressed = 0 + padded = size + padding(size) + while True: + chunk = stream.read(CHUNK) + if not chunk: + break + compressed += len(chunk) + if decoder.eof or (wire_size is not None and compressed > wire_size): + raise PorterError("unexpected bytes after gzip member") + pending = chunk + while True: + try: + data = decoder.decompress(pending, CHUNK) + except zlib.error as exc: + raise PorterError("corrupt gzip member") from exc + file_part = min(len(data), max(0, size - decoded)) + hasher.update(data[:file_part]) + decoded += len(data) + if decoded > padded or any(data[file_part:]) or decoder.unused_data: + raise PorterError("invalid gzip member length or tar padding") + pending = decoder.unconsumed_tail + if decoder.eof or (not pending and len(data) < CHUNK): + break + if send is not None: + send(chunk) + if (not decoder.eof or decoded != padded or hasher.hexdigest() != digest + or (wire_size is not None and compressed != wire_size)): + raise PorterError("truncated gzip member or object digest mismatch") + + +def stream_archive(repo, entries, reply): + headers = [] + objects = {} + end = gzip_member(bytes(2 * BLOCK)) + length = len(end) + for entry in entries: + header = gzip_member(archive_header(entry)) + headers.append(header) + length += len(header) + if entry["kind"] == "file": + digest = entry["sha256"] + if digest not in objects: + path = object_path(repo, digest) + objects[digest] = (path, regular_info(path)) + length += objects[digest][1].st_size + + reply(f"OK {length}\n".encode("ascii")) + for header, entry in zip(headers, entries): + reply(header) + if entry["kind"] == "file": + digest = entry["sha256"] + path, info = objects[digest] + with regular_stream(path, info) as stream: + check_member(stream, digest, entry["size"], reply, info.st_size) + reply(end) + + +def catalog(repo): + for path in (repo / "publications").iterdir(): + if path.suffix != ".json" or not PUBLICATION_ID.fullmatch(path.stem): + continue + raw = read_metadata(path) + record = parse_json(raw) + if not isinstance(record, dict) or record.get("id") != path.stem: + raise PorterError("invalid publication record") + yield raw + b"\n" + + +def serve_porter(repo, line, recv, send): + """Return false for the legacy protocol. A started response ends at EOF.""" + fields = line.split() + if not fields or fields[0] not in ("CATALOG", "MANIFEST", "ARCHIVE"): + return False + if repo is None: + send(b"NO Porter repository is disabled\n") + return True + started = False + + def reply(data): + nonlocal started + started = True + send(data) + + try: + if fields == ["CATALOG"]: + reply(b"OK\n") + for row in catalog(repo): + reply(row) + reply(b".\n") + elif fields[0] == "MANIFEST" and len(fields) == 2: + raw, _ = load_manifest(repo, fields[1]) + reply(f"OK {len(raw)}\n".encode("ascii")) + reply(raw) + elif fields[0] == "ARCHIVE" and len(fields) in (2, 3): + _, manifest = load_manifest(repo, fields[1]) + entries = manifest["entries"] + if len(fields) == 3: + if not re.fullmatch(r"[0-9]{1,6}", fields[2], re.ASCII): + raise PorterError("invalid selection length") + remaining = int(fields[2]) + if not 0 < remaining <= MAX_SELECTION: + raise PorterError("invalid selection length") + request = bytearray() + while remaining: + part = recv(min(CHUNK, remaining)) + if not part: + raise PorterError("truncated selection") + request.extend(part) + remaining -= len(part) + selected = parse_json(bytes(request)) + if (not isinstance(selected, list) or len(selected) > len(entries) + or any(type(i) is not int or not 0 <= i < len(entries) for i in selected) + or selected != sorted(set(selected))): + raise PorterError("invalid entry selection") + entries = [entries[index] for index in selected] + stream_archive(repo, entries, reply) + else: + raise PorterError("invalid Porter request") + except (PorterError, OSError) as exc: + # A partial archive must end below its advertised length and without + # the tar terminator. The diagnostic stays on the serving host. + print(f"os64serve: Porter request failed: {exc}") + if not started: + send(b"NO invalid request or unavailable package\n") + return True diff --git a/tools/test_porter.py b/tools/test_porter.py new file mode 100644 index 000000000..b2290b1ee --- /dev/null +++ b/tools/test_porter.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""Porter publication, wire compatibility and archive regression tests.""" + +from contextlib import contextmanager +import gzip +import hashlib +import io +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import sys +import tarfile +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch +import zlib + +import porter_store as store + +if os.name != "nt": + import porter_publish as publisher + + +TOOLS = Path(__file__).resolve().parent +CHECKOUT = TOOLS.parent + + +def repository(root): + for name in ("objects", "manifests", "publications"): + (root / name).mkdir(parents=True) + return root + + +def file_entry(repo, lot, path, data): + digest = hashlib.sha256(data).hexdigest() + store.object_path(repo, digest).write_bytes(store.gzip_member(data + bytes(store.padding(len(data))))) + return {"lot": lot, "path": path, "kind": "file", "sha256": digest, "size": len(data)} + + +def publish_fixture(repo, entries): + manifest = {"version": 1, "scope": "media", "kernel": None, "lots": ["media"], "entries": entries} + store.check_manifest(manifest) + raw = store.canonical(manifest) + target = hashlib.sha256(raw).hexdigest() + (repo / "manifests" / f"{target}.json").write_bytes(raw) + identifier = "1" * 32 + record = {"id": identifier, "targets": {"media": target}, "name": "Tape & clip"} + (repo / "publications" / f"{identifier}.json").write_bytes(store.canonical(record)) + (repo / "publications" / ".incoming-catalog-test").write_bytes(b"{") + return target, raw, record + + +@contextmanager +def server(repo, *legacy_dirs): + args = [sys.executable, "-u", str(TOOLS / "os64serve.py"), "--porter-repo", str(repo), + "--bind", "127.0.0.1", "--port", "0", *map(str, legacy_dirs)] + with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as proc: + failed = False + try: + line = proc.stdout.readline() + if not line.startswith("os64serve: serving on 127.0.0.1:"): + raise AssertionError(f"server startup: {line}") + yield int(line.rsplit(":", 1)[-1]) + except BaseException: + failed = True + raise + finally: + if proc.poll() is None: + proc.terminate() + output, _ = proc.communicate(timeout=10) + if failed: + print(output, file=sys.stderr, end="") + + +def request(port, line, body=b""): + with socket.create_connection(("127.0.0.1", port), timeout=15) as conn: + conn.sendall(line.encode("ascii") + b"\n" + body) + conn.shutdown(socket.SHUT_WR) + with conn.makefile("rb") as reply: + return reply.readline(), reply.read() + + +def archive_payload(header, body): + status, size = header.split() + if status != b"OK" or int(size) != len(body): + raise AssertionError((header, len(body))) + return body + + +class LoopbackTests(unittest.TestCase): + """Run this class on native Windows as well as Linux.""" + + def test_catalog_manifest_full_selective_and_legacy(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + repo = repository(root / "Porter repo") + legacy = root / "Legacy bin" + legacy.mkdir() + (legacy / "hello").write_bytes(b"hello") + samples = {"0 bytes": b"", "511 bytes": b"a" * 511, + "512 bytes": b"b" * 512, "513 bytes": b"c" * 513, + "café bytes": b"d"} + entries = [ + {"lot": "media", "path": "Empty directory", "kind": "dir"}, + *[file_entry(repo, "media", name, content) for name, content in samples.items()], + file_entry(repo, "media", "repeat", samples["513 bytes"]), + ] + entries.sort(key=lambda entry: entry["path"]) + target, manifest, record = publish_fixture(repo, entries) + with server(repo, f"{legacy}=tools") as port: + crc = zlib.crc32(b"hello") + self.assertEqual(request(port, "LIST"), (f"hello 5 {crc:08x} tools\n".encode(), b".\n")) + self.assertEqual(request(port, "GET hello"), (f"OK 5 {crc:08x}\n".encode(), b"hello")) + self.assertEqual(request(port, "CATALOG"), (b"OK\n", store.canonical(record) + b"\n.\n")) + self.assertEqual(request(port, f"MANIFEST {target}"), + (f"OK {len(manifest)}\n".encode(), manifest)) + self.assertTrue(request(port, "MANIFEST " + "../" * 21)[0].startswith(b"NO ")) + raw = archive_payload(*request(port, f"ARCHIVE {target}")) + self.assertEqual(gzip.decompress(raw)[-1024:], bytes(1024)) + with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive: + for name, expected in dict(samples, repeat=samples["513 bytes"]).items(): + self.assertEqual(archive.extractfile(f"media/{name}").read(), expected) + self.assertTrue(archive.getmember("media/Empty directory").isdir()) + self.assertEqual(len(archive.getmembers()), len(entries)) + selection = [0, 3] + encoded = store.canonical(selection) + raw = archive_payload(*request(port, f"ARCHIVE {target} {len(encoded)}", encoded)) + with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive: + self.assertEqual(archive.getnames(), ["media/" + entries[i]["path"] for i in selection]) + for selection in ([3, 0], [0, 0], [-1], [True], [len(entries)]): + encoded = store.canonical(selection) + self.assertTrue(request(port, f"ARCHIVE {target} {len(encoded)}", encoded)[0].startswith(b"NO ")) + self.assertTrue(request(port, f"ARCHIVE {target} 100", b"[]")[0].startswith(b"NO ")) + self.assertTrue(request(port, f"ARCHIVE {target} {store.MAX_SELECTION + 1}")[0].startswith(b"NO ")) + + def test_corrupt_truncated_and_missing_objects(self): + with tempfile.TemporaryDirectory() as temp: + repo = repository(Path(temp) / "repo") + data = b"correct" + entry = file_entry(repo, "media", "sample", data) + target, _, _ = publish_fixture(repo, [entry]) + obj = store.object_path(repo, entry["sha256"]) + encoded = obj.read_bytes() + with server(repo) as port: + self.assertTrue(request(port, "GET porter_store.py")[0].startswith(b"NO ")) + for broken in ( + encoded[:-2], + encoded[:-1] + bytes([encoded[-1] ^ 1]), + encoded + store.gzip_member(b""), + store.gzip_member(b"X" * len(data) + bytes(store.padding(len(data)))), + store.gzip_member(data + b"X" * store.padding(len(data))), + ): + obj.write_bytes(broken) + header, partial = request(port, f"ARCHIVE {target}") + self.assertLess(len(partial), int(header.split()[1])) + obj.unlink() + self.assertTrue(request(port, f"ARCHIVE {target}")[0].startswith(b"NO ")) + self.assertEqual(request(port, "CATALOG")[0], b"OK\n") + + +class FileSnapshotTests(unittest.TestCase): + def test_windows_path_and_handle_timestamps_use_separate_snapshots(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "object.gz" + path.write_bytes(b"contents") + named = path.stat() + fields = {field: getattr(named, field) for field in ( + "st_dev", "st_ino", "st_mode", "st_size", "st_mtime_ns", "st_ctime_ns" + )} + opened = SimpleNamespace(**dict(fields, st_ctime_ns=fields["st_ctime_ns"] + 1)) + windows = dict(vars(os), name="nt", fstat=lambda fd: SimpleNamespace(**vars(opened))) + with patch.object(store, "os", SimpleNamespace(**windows)): + with store.regular_stream(path, named) as handle: + self.assertEqual(handle.read(), b"contents") + with self.assertRaisesRegex(store.PorterError, "changed while reading"): + with store.regular_stream(path, named): + opened.st_ctime_ns += 1 + opened.st_ino += 1 + with self.assertRaisesRegex(store.PorterError, "changed while opening"): + with store.regular_stream(path, named): + self.fail("opened an object with a different identity") + + +@unittest.skipIf(os.name == "nt", "Make publisher runs on Linux") +class PublisherTests(unittest.TestCase): + def setUp(self): + scratch = tempfile.TemporaryDirectory(prefix="porter-tests-") + self.addCleanup(scratch.cleanup) + self.root = Path(scratch.name) + self.checkout = self.root / "checkout A" + self.checkout.mkdir() + (self.checkout / "tools").mkdir() + shutil.copyfile(CHECKOUT / "GNUmakefile", self.checkout / "GNUmakefile") + for name in ("porter_store.py", "porter_publish.py"): + shutil.copyfile(TOOLS / name, self.checkout / "tools" / name) + (self.checkout / ".gitignore").write_text("disk/\nporter-sources.conf\n", encoding="utf-8") + self.run_git("init", "-q", "-b", "preview") + self.run_git("add", ".") + self.run_git("-c", "user.name=Porter test", "-c", "user.email=porter@invalid", "commit", "-qm", "fixture") + self.repo = self.root / "publication repo" + self.env = dict(os.environ, NAME="ambient label") + self.sources = self.checkout / "porter-sources.conf" + + def run_git(self, *args): + subprocess.run(["git", *args], cwd=self.checkout, check=True, capture_output=True) + + def args(self, *options): + return ["make", "package", f"PORTER_REPO={self.repo}", *options] + + def package(self, *options, success=True): + result = subprocess.run(self.args(*options), cwd=self.checkout, env=self.env, + text=True, capture_output=True, timeout=30) + self.assertEqual(result.returncode == 0, success, result.stdout + result.stderr) + return result.stdout + result.stderr + + def records(self): + return [json.loads(record) for record in store.catalog(self.repo)] + + def load(self, digest): + return store.load_manifest(self.repo, digest)[1] + + def test_concurrency_dedup_removal_empty_nested_and_labels(self): + media = self.root / "media root" + media.mkdir() + (media / "empty").mkdir() + (media / "clip 1").write_bytes(b"same bytes") + (media / "clip 2").write_bytes(b"same bytes") + (media / "excluded link").symlink_to(media / "clip 1") + nested = media / "separate" + nested.mkdir() + (nested / "solo").write_bytes(b"other bytes") + self.sources.write_text(f"[sources media]\nmedia += {media}\n[sources sound]\nsounds += {nested}\n") + other = self.root / "checkout B" + shutil.copytree(self.checkout, other) + options = self.args("SCOPES=media,sound", "NAME=Repeated title", "BASELINE=1") + with (subprocess.Popen(options, cwd=self.checkout, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as first, + subprocess.Popen(options, cwd=other, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as second): + for proc in (first, second): + self.assertIn(b"excluded link", (output := proc.communicate(timeout=30))[1]) + self.assertEqual(proc.returncode, 0, output) + first, second = self.records() + self.assertNotEqual(first["id"], second["id"]) + self.assertEqual(first["targets"], second["targets"]) + self.assertEqual(first["name"], "Repeated title") + self.assertTrue(first["baseline"]) + self.assertNotIn(str(self.root), json.dumps(first)) + self.assertEqual(len(list((self.repo / "objects").glob("*.gz"))), 2) + media_id = first["targets"]["media"] + self.assertEqual([entry["path"] for entry in self.load(media_id)["entries"]], ["clip 1", "clip 2", "empty"]) + self.assertEqual([entry["path"] for entry in self.load(first["targets"]["sound"])["entries"]], ["solo"]) + + for path in (media / "clip 1", media / "clip 2", media / "excluded link"): + path.unlink() + (media / "empty").rmdir() + self.package("SCOPES=media") + last = next(row for row in self.records() if row["name"].startswith("preview ")) + self.assertIn("T", last["published_at"]) + self.assertFalse(last["baseline"]) + self.assertEqual(self.load(last["targets"]["media"])["entries"], []) + self.assertEqual(self.load(last["targets"]["media"])["lots"], ["media"]) + self.assertEqual(len(self.load(media_id)["entries"]), 3) + self.assertEqual(len(list((self.repo / "objects").glob("*.gz"))), 2) + shutil.rmtree(media) + with server(self.repo) as port: + data = archive_payload(*request(port, f"ARCHIVE {media_id}")) + with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: + self.assertEqual(archive.extractfile("media/clip 1").read(), b"same bytes") + + def test_collision_missing_source_dry_run_and_path_boundary(self): + roots = [self.root / first for first in ("first root", "second root")] + for root in roots: + root.mkdir() + sources = "[sources media]\n" + "".join(f"tape += {root}\n" for root in roots) + self.sources.write_text(sources) + for root, data in zip(roots, (b"one", b"two")): + (root / "same").write_bytes(data) + result = self.package("SCOPES=media", success=False) + self.assertIn("conflicting tape/same", result) + for root in roots: + self.assertIn(str(root), result) + self.assertEqual(self.records(), []) + shutil.rmtree(roots[1]) + self.assertIn(str(roots[1]), self.package("SCOPES=media", success=False)) + self.assertEqual(self.records(), []) + self.package("SCOPES=media", "-n") + self.assertEqual(self.records(), []) + + roots[1].mkdir() + (roots[1] / "same").write_bytes(b"one") + parent = roots[0] / ("a" * 70) / ("b" * 79) + parent.mkdir(parents=True) + long_file = parent / ("c" * 99) + long_file.write_bytes(b"one") + self.package("SCOPES=media", "NAME=Path boundary") + entries = self.load(self.records()[0]["targets"]["media"])["entries"] + filenames = [e for e in entries if e["kind"] == "file"] + self.assertEqual(len(filenames), 2) + self.assertEqual(max(len("tape/" + e["path"]) for e in filenames), 255) + + def test_changed_source_and_corrupt_reuse(self): + objdir = repository(self.repo) + source = self.root / "movie" + source.write_bytes(b"first") + item = publisher.Input("media", "tape", "movie", source, source.stat()) + read = publisher.read_source + + def change_after_hash(current, member=None): + digest = read(current, member) + if member is None: + source.write_bytes(b"second") + return digest + + with patch.object(publisher, "read_source", side_effect=change_after_hash): + with self.assertRaisesRegex(store.PorterError, "file changed"): + publisher.capture(objdir, item, {}) + self.assertEqual(list((objdir / "objects").iterdir()), []) + item = publisher.Input("media", "tape", "movie", source, source.stat()) + digest = publisher.capture(objdir, item, {}) + path = store.object_path(objdir, digest) + with patch.object(publisher.gzip, "GzipFile", side_effect=AssertionError("unexpected recompression")): + self.assertEqual(publisher.capture(objdir, item, {}), digest) + path.write_bytes(b"corrupt") + with self.assertRaisesRegex(store.PorterError, "corrupt gzip"): + publisher.capture(objdir, item, {}) + self.assertEqual(path.read_bytes(), b"corrupt") + + def test_inventory_changes_during_collection(self): + repo = repository(self.repo) + assets = self.root / "assets" + assets.mkdir() + (assets / "first").write_bytes(b"one") + self.sources.write_text(f"[sources media]\nmedia += {assets}\n") + source_files = [(self.sources, True)] + build = publisher.read_sources(self.checkout, repo, source_files) + capture = publisher.capture + + def add_file(store_root, item, checked): + digest = capture(store_root, item, checked) + (assets / "added during scan").touch() + return digest + + with patch.object(publisher, "capture", side_effect=add_file): + with self.assertRaisesRegex(store.PorterError, "changed during publication"): + publisher.publish_targets(self.checkout, repo, ["media"], [], source_files, build) + self.assertEqual(self.records(), []) + + +if __name__ == "__main__": + unittest.main()