Files
Library/docs/roadmap/modules/Archive.md

151 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Archive — safe streaming and atomic publication
Status: plan; all implementation tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
R-003/R-006/R-014/R-015 and [C-02–C-07](../ARCHITECTURE.md) apply.
## Existing extraction contract
[Archive.hpp](../../../include/Void/Archive/Archive.hpp) exposes
`Void::Archive::extract(path, destination, ExtractionOptions)` returning an ExtractionResult.
Defaults are 10,000 entries, 512 MiB per file, 2 GiB total and no overwrite.
[Archive.cpp](../../../src/Archive/Archive.cpp) enables tar plus none/zstd filters through
libarchive, rejects absolute/non-normal/traversal/backslash paths, duplicates, links and
special entries, and checks declared and actual extracted bytes. POSIX extraction pins the
destination directory, walks parents with descriptor-relative no-follow operations, writes
temporary regular files, syncs them and publishes them. Windows has a different path-based
implementation; identical race resistance is not established by the Unix source.
[module.cmake](../../../src/Archive/module.cmake) links Functional and LibArchive::LibArchive.
[Tests](../../../tests/standalone/Archive/Archive.cpp) include bounded tar.zstd extraction,
explicit directories, traversal/links, symlink parents, destination path swapping and actual
size limits. These are regression obligations. A failed whole extraction can still leave
earlier successfully published entries: the existing per-file workflow is not an atomic
replacement of an entire directory tree.
## Backend and API completion
Retain libarchive as the initial tar/zstd decoder and later encoder. Void owns path policy,
resource admission, stream adapters and publication transactions. Native directory safety
logic is preferable to shelling out; a new tar or zstd implementation would add compatibility
and security risk without a measured requirement. Other formats require an explicit tested
profile; enabling every decoder by default is not part of completion.
NEW illustrative surface in the existing namespace; shared operation options come from
[Async](Async.md), byte streams from [IO](../subsystems/IO.md):
```cpp
struct EntryInfo; // owned normalized path, type, declared size, safe mode
struct ReadLimits; // policy defaults below
class Reader; // caller-driven next_entry/read_chunk/skip_entry
class StagedTree; // owns unpublished directory and cleanup obligation
Result<Reader> open_reader(InputStream&, ReadLimits);
Result<StagedTree> extract_staged(InputStream&, DirectoryHandle, ExtractionOptions);
Result<PublicationReceipt> publish(StagedTree, std::string_view new_child_name);
Result<void> create_archive(OutputStream&, EntrySource&, CreationOptions);
```
All types except existing ExtractionOptions are NEW Archive or IO-owned interfaces as
indicated; this sketch is not a compiling example. Input/output streams are borrowed through
completion, or moved into an owning async operation. EntryInfo never points into libarchive's
next-header scratch buffer. Reader has one active entry; callers drain or explicitly skip it
before advancing. Skipping still accounts for decompressed work and limits, not just stored
bytes. The reader never materializes a complete archive by default.
Listing is a bounded metadata traversal and carries the same path/entry-count validation.
An opt-in forensic listing may report rejected metadata without writing anything, but is
not a way to authorize extraction of unsafe entries. Archive creation accepts regular files
and directories only, sorts normalized paths, rejects duplicates, and uses reproducible
timestamps/owners/modes when requested. It does not follow links while enumerating sources.
## Atomic extraction workflow
`extract_staged` creates an exclusive private child beneath a caller-owned parent directory,
pins its descriptor, then extracts all content there. Default output permissions are 0644
files and 0755 directories, retaining only the explicitly allowed executable bit policy;
ignore ownership, setuid/setgid, device metadata and extended attributes. File paths have a
4 KiB encoded limit, 255-byte component limit and 64 components. Reject conflicts where
a file is required to be a parent directory, including case-collisions on a backend that
cannot distinguish them. Do not repair malicious paths by normalizing them into acceptance.
On success, close/sync every file, sync created directories bottom-up, write a bounded
completion inventory, sync the staging root, and return StagedTree. Publication creates a
previously absent immediate child name by a no-replace directory rename on the same filesystem,
then syncs the parent. An unsupported atomic no-replace primitive returns UnsupportedCapability;
there is no fallback to a racy existence-check plus overwrite. Existing nonempty directories
are never recursively overwritten under an "atomic" label.
Replacing an application version uses immutable version directories and a separate pointer/
activation owner, such as [Update](Update.md)'s VersionStore. Archive does not invent a new
update commit point. If parent sync fails after rename, PublicationReceipt/error records
Unknown outcome and the destination/staging identity so recovery can inspect it. It cannot
claim the published tree was rolled back. Cancellation before publication cleans only the
owned staging tree; after publication it reports the known/unknown publication outcome.
All filesystem accesses stay relative to retained directory handles on the hardened Linux
path. Untrusted siblings cannot redirect extraction by swapping parent paths. Cleanup removes
only names created under that owned staging descriptor and never follows links. Cleanup
failure preserves the primary error and a retryable staging identifier, rather than masking
the original decode/write error. Startup cleanup requires an exclusive operation marker and
age/ownership validation, not a broad deletion of directories matching a prefix.
## Bounds, cancellation and diagnostics
Retain current file/total/entry defaults. NEW streaming defaults add a 64 KiB transfer buffer,
8 MiB aggregate path/inventory metadata, four active jobs and 16 pending jobs per explicit
managed service, and a 1 GiB compressed-input cap. Reject zero limits as invalid except an
explicit zero-entry policy. Actual decompressed bytes count even when the format omits or
lies about size; checked subtraction prevents arithmetic wrap. Nesting archives is never
automatic. High compression ratios are allowed only within absolute limits.
Cooperative checks happen between headers and chunks, but do not make a codec call forcibly
interruptible. The NEW hardened untrusted-input profile uses a System-owned child job with
128 MiB RSS and 60-second total execution defaults, plus bounded result/output channels;
the parent holds publication authority and verifies the staged tree before publishing.
Platforms unable to enforce that profile report the capability gap. Ordinary embedded
trusted-input mode can call the decoder synchronously with documented cooperative limits.
Neither mode promises that a 64 KiB IO buffer bounds the decoder's internal memory.
Domain errors distinguish unsafe entry, unsupported format, corrupt archive, limit exceeded,
permission, no space, cancellation, timeout and unknown publication. Diagnostics cap path
rendering at 4 KiB and avoid writing attacker-controlled newlines unescaped. Progress callbacks
run outside shared locks, own their event data if retained, and are rate-limited to 10 Hz
per job. Failure to deliver progress never changes extraction success.
## Ordered work
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| M-ARCHIVE-01 | P0; existing tests | Characterize partial-tree failure, exact accepted path/type policy and platform capabilities; preserve all existing anti-traversal tests. | astra_implementer |
| M-ARCHIVE-02 | P1; M-ARCHIVE-01, IO stream ownership, Binary bounds | Reader/listing and chunk adapters, metadata limits and typed errors; truncated/adversarial input cannot exceed accounted limits. | sol_implementer |
| M-ARCHIVE-03 | P2; M-ARCHIVE-02, IO directory durability | StagedTree and atomic no-replace publication; crash at each sync/rename recovers either unpublished staging or a complete published tree. | astra_implementer |
| M-ARCHIVE-04 | P2; M-ARCHIVE-02/03, System process limits | Hardened decoder isolation, cancellation/cleanup and race fixtures; parent never publishes unvalidated/partial child output. | astra_implementer |
| M-ARCHIVE-05 | P3; M-ARCHIVE-03, Update package contract | Reproducible creation and package inventory verification; create/extract roundtrip preserves only allowed metadata and Update retains activation ownership. | sol_implementer |
| M-ARCHIVE-06 | P3; M-ARCHIVE-04/05, shared harness | Fuzz corpus, filesystem fault campaign and decoder performance profiles; publish capability matrix before a new format/backend is accepted. | sol_implementer |
P4 snapshot/package transport reuses bounded archives; a replicated snapshot's correctness
and installation marker belong to [Replication](../subsystems/Replication.md), not tar metadata.
## Verification and compatibility
CURRENT TEMPLATE: `<existing-build>/tests/VoidTests --filter '^archive_'`, backed by the
test names above. [Validation](../VALIDATION.md) contains actual build evidence; no rerun
occurred here. PROPOSED after M-ARCHIVE-02–06: malformed headers/zstd, duplicate/conflicting
paths, long names, symlink swap at each parent, partial write/disk full/sync failure,
cancellation during decode/publication, unsafe staging cleanup, resource-killed child and
Windows capability fixtures. Include create→extract property tests and an independent
tar consumer when validating generated packages; fixtures must not invoke production paths.
[Performance](../PERFORMANCE.md) profiles many tiny files, a few large files, incompressible
data and compression bombs within test limits. Record p50/p95/p99 completion/admission,
bytes/s, allocations, peak RSS/CPU including decoder child, disk amplification and build cost.
The common repetition/confidence and regression rules apply; security checks remain enabled.
[Migration](../MIGRATION.md) keeps `extract` as the documented incremental API. New callers
needing all-or-nothing visibility use extract_staged→publish and handle Unknown explicitly.
Never change overwrite defaults silently. Rollback of an unselected new workflow can retain
legacy extraction; rollback of a published tree is owned by the consuming application.
New formats are version/profile gated. [Build/distribution](../BUILD-AND-DISTRIBUTION.md)
keeps libarchive optional outside Archive consumers. Graph partial ranges in the header and
test helper were read directly; cited source/test files were checked for coverage. No new
atomicity, fuzz, portability or measured-performance result is claimed.