SPB Git

Repository Public

CosmosDataPacks.md 17.3 KB

# CosmosDataPacks

Manifests, integrity, storage, download and installation of data packs. Depends on CosmosCore and Apple frameworks only (Foundation, CryptoKit, Compression). Nothing is ever downloaded on the module's own initiative: the only network calls are PackManager.refreshIndex() and PackManager.install(_:), both explicit, and the index URL defaults to none.

File Content
PackManifest.swift PackManifest (schema v1), SemanticVersion, LocalizedText, PackKind, Redistribution, PackFile, PackSource, PackDependency, PackSignatureInfo, PackPath
PackIndex.swift PackIndex, PackIndexEntry, PackIndexLoader, PackURLPolicy
PackArchive.swift, PackExtractor.swift ustar reader/writer, bounded streaming gunzip, validating extraction and directory import
PackStore.swift PackStore actor, configuration, quotas, inventory, usage, verification, install/upgrade, recovery, removal, export
PackDownloader.swift PackDownloader, PackDownloadRequest, PackDownloadPolicy, PackDownloadControl
PackSignature.swift PackSignature, TrustedPackKey, PackSignatureState
PackManager.swift PackManager actor and PackOffer: the facade for the pack manager screen
PackHash.swift, JSONValue.swift, PackError.swift streaming SHA-256, loss-free JSON tree, error type

# 1. Manifest schema version 1 (manifest.json)

JSON Schema: DataPipeline/packs/schema/pack-manifest.v1.schema.json (a test checks that its keys are those of the Swift model). The writer emits sorted keys, 2-space indentation, a trailing newline.

Key Type Req. Meaning
schemaVersion integer yes Must be 1. Any other value is refused with unsupportedSchemaVersion (not "invalid").
id string yes [a-z0-9][a-z0-9._-]{0,63}; also the directory name of the installed pack.
version string yes Semantic version 2.0.0 (major.minor.patch[-pre][+build]).
kind string yes ephemeris, catalogue, textures, sky-imagery, missions, satellites, time, other.
title object yes {"en": …, "fr": …}; en mandatory.
description object no Same shape as title.
installedSize integer yes Bytes; must equal the sum of files[].size.
downloadSize integer no Archive size when the builder knows it. The pack index is authoritative.
files array yes path (relative, /-separated), size (bytes), sha256 (64 lower-case hex); optional role, description, source (id of a sources[] entry), url (upstream URL of that file). Other keys are preserved.
sources array no id, name, version, license required; url, retrieved (ISO date), citation, method optional. Maps one-to-one onto CosmosCore.Provenance (PackManifest.provenance). No other key allowed.
license string no Licence summary of the pack as a whole.
coverage any JSON no Free-form structured coverage (time span, magnitude limit, object counts…).
redistribution string yes redistributable or localBuildOnly. Only the former can be exported or listed in an index.
dependencies array no { "id", "minimumVersion"? }.
minimumAppVersion string no Semantic version of the oldest application able to read the pack.
signature object no { "algorithm": "ed25519", "keyID": …, "file": "manifest.sig" } — announces the detached signature.
anything else any no Extension keys (domain data such as missions, file_format) are kept verbatim in PackManifest.extensions.

Path rules (PackPath.validate, applied to the manifest, to archive entries and to directory imports): not empty, ≤ 1024 bytes, components ≤ 255 bytes, no leading / or ~, no ./../empty component, no backslash, no NUL or control character (C0, DEL, C1), no line separator or bidirectional control, no component ending in a space or a dot, first component not starting with a dot (reserved for the store), not manifest.json/manifest.sig in any letter case. Two paths may not be equal, differ only by case or Unicode normalisation, or use one name both as a file and as a directory (PackPath.checkCollisions).

Legacy aliases accepted on read, never written: format → schemaVersion, licence → license, total_bytes → installedSize, title as a plain string → title.en; in files[]: name → path, bytes → size, provenance_id → source; in sources[]: licence → license.

# 2. Pack index (PackIndex, schema version 1)

JSON Schema: DataPipeline/packs/schema/pack-index.v1.schema.json. { "schemaVersion": 1, "generated"?, "packs": [entry] } where an entry has id, version, kind, title, description?, installedSize, archiveSize, license, coverage?, redistribution, archiveURL (absolute, or relative to the index), archiveSHA256, minimumAppVersion?, dependencies, signatureKeyID?. Loaded from a file: URL or over HTTPS (PackIndexLoader); the location is PackManagerConfiguration.indexURL, nil by default. PackManager.offers() joins the index with the store: sizes, licence, version, coverage, free space, remaining download bytes and the list of blockers (quota, disk, application version, missing dependencies) are all available before a single byte of an archive is requested.

# 3. Archive format (.orixpack)

A POSIX ustar stream, optionally wrapped in gzip (detected by magic number):

  1. manifest.json — always the first entry;
  2. manifest.sig — optional, second;
  3. the payload files, each exactly once, any order (the tools write manifest order);
  4. two zero blocks, then at most 1 MiB of zero padding.

Why ustar: it is a sequence of 512-byte headers each followed by its data, so it is read strictly forward in 1 MiB chunks without ever holding a pack in memory; with the manifest first, every entry is checked before its first byte is written; the standard tar/tarfile tools can inspect an archive; and the Python standard library can produce it, which keeps the pipeline free of dependencies. Packs are mostly incompressible (JPEG/PNG textures, Chebyshev coefficients), so compression is optional: gzip is read through the system Compression framework (compression_stream, raw DEFLATE) with two fixed 64 KiB buffers. The writers are deterministic (mode 0644, uid/gid 0, mtime 0): PackStore.exportArchive and packtool.py build give byte-identical archives for the same pack (tested).

Restrictions: regular files only; no pax or GNU extensions (paths ≤ 100 bytes, or ≤ 255 with a / split that fits the ustar prefix field); one file ≤ 8 GiB − 1; the gzip CRC-32 trailer is not checked (integrity rests on the SHA-256 of the archive and of every file).

# 4. Store

text
<bundle>/Contents/Resources/Packs/<id>/…          starter packs, read-only (PackStoreConfiguration.bundledRoot)
<Application Support>/<app>/Packs/<id>/…          user packs      (PackStoreConfiguration.userRoot)
                               .staging/<uuid>/   extraction in progress
                               .journal/<id>.json installation in flight
                               .previous/<id>/    previous version (move-aside strategy only)
                               .downloads/        partial and completed archives (*.part, *.part.json)

Both roots are injected. PackStoreConfiguration.defaultUserRoot(applicationDirectoryName:) asks FileManager for the user's Application Support directory (the container's one in a sandbox) and creates nothing; no home path is hard-coded.

Precedence for an id present in both places: the user copy is active when its version is ≥ the bundled one; otherwise the bundled copy is active and the user copy is reported inactive with the suggestion .removeUserCopy. PackStore.url(forPack:file:) resolves in the active copy, only for paths listed in the manifest, and only to regular files.

Verification (verify) re-hashes every listed file and walks the directory: missing, modified (size, content, or no longer a regular file), extra (unlisted files, symbolic links included), signature state, and repair suggestions (reinstall, deleteExtraFiles, removeUserCopy, reinstallApplication).

Quotas: PackQuotas(perPack:total:) on the declared installed sizes of user packs; free space through the injectable PackEnvironment.freeSpace plus freeSpaceMargin (256 MiB by default). All are checked after the manifest is read and before any payload byte is written; checkCapacity exposes the same check to the UI.

# 5. Atomic installation and recovery

staging directory (same volume) → validated extraction → journal → commit → cleanup.

  • Commit of a first installation: one rename(2).
  • Commit of an upgrade: renamex_np(RENAME_SWAP) exchanges the staged and the installed directories in one step (the pack directory is never absent); when the volume refuses, the previous version is renamed to .previous/<id> and the new one renamed in — the journal covers that gap.
  • The journal names the staging directory and a token file placed in the staged pack. At launch PackStore.recover() (PackManager.start()): token present in the live directory → the commit happened, leftovers are deleted; otherwise the previous version is put back if it had been moved, and the staging directory is deleted. Orphan staging directories are removed. The operation is idempotent.
  • The previous version is not touched until the new one has passed every check.
  • Files are fsynced; the directory renames themselves are not followed by F_FULLFSYNC (see limitations).

# 6. Download

PackDownloader (URLSession with a delegate, ephemeral configuration, no cache, Accept-Encoding: identity):

  • HTTPS only; http://127.0.0.1|localhost|::1 is accepted only with allowInsecureLoopback (tests). Redirects are subject to the same rule.
  • Resume: partial file <name>.part + <name>.part.json (URL, ETag, Last-Modified, total). A later call sends Range: bytes=N- and If-Range: <ETag or Last-Modified>; 206 with the expected Content-Range appends, 200 restarts from zero (resource changed or server without range support), 416 discards the partial file. A partial file without validator is never resumed.
  • The size limit (maximumSize, and the size announced by the index) is checked on the response headers and again on every chunk written.
  • Retries: transient failures only (network errors, 408/425/429/5xx, short body), maximumRetries times with exponential backoff capped by maximumBackoff; each retry resumes.
  • Pause/cancel: PackDownloadControl.pause() keeps the partial file (PackError.paused), cancel() or cancelling the Swift task deletes it (PackError.cancelled).
  • The file reaches its destination only after its size and SHA-256 match the index. PackError.offline when the device has no connectivity or the host cannot be reached; nothing is installed.

# 7. Signatures

Ed25519 (CryptoKit.Curve25519.Signing) over the exact bytes of manifest.json; since the manifest lists the SHA-256 of every file, the signature covers the whole pack. manifest.sig is {"algorithm": "ed25519", "keyID": …, "signature": base64}; the default key id is the first 16 hex digits of the SHA-256 of the raw public key. PackSignatureState: trusted(keyID), unsigned, untrustedKey(keyID), invalid(reason); it is recomputed at every enumeration and exposed on InstalledPack.signature (description gives e.g. "unsigned – local/import").

Situation Download (requireTrusted) Local import (allowUnsignedLocal)
valid signature, trusted key installed installed
no signature refused installed, state unsigned
signature by an unknown key refused installed, state untrustedKey
signature does not verify / announced but absent / key id mismatch / unreadable refused refused

The trusted keys come from PackStoreConfiguration.trustedKeys; the module ships none.

# 8. Threat model and tested mitigations

The archive, the index, the server and an imported directory are untrusted. Each line is exercised by a test with a hand-crafted input (ArchiveSecurityTests, StoreTests, DownloadTests).

Attack Mitigation Error
Absolute path, .., ., empty component PackPath.validate on every entry before any write unsafePath
Symbolic link, hard link, device, FIFO, directory, pax/GNU header only regular-file entries are accepted; directory import uses lstat and O_NOFOLLOW unsupportedEntryType
Entry not listed in the manifest lookup in the manifest before writing unlistedEntry
Duplicate entry, second manifest.json/manifest.sig each listed file accepted once; files created with O_EXCL duplicateEntry
Size or hash different from the manifest header size compared before writing; SHA-256 computed while writing sizeMismatch, hashMismatch
Missing file checked at the end marker missingEntry
Expansion bomb (in an entry, after the end marker, oversized manifest) declared sizes bound every read; ≤ 1 MiB of trailing zeros; manifest ≤ 32 MiB sizeMismatch, malformedArchive, expansionLimitExceeded
Size beyond quota or disk checked on the manifest before the payload quotaExceeded, insufficientDiskSpace
NUL (smuggled suffix), control characters, invalid UTF-8 in names header fields must be NUL-padded only, valid UTF-8, no control character unsafePath
Case / Unicode-normalisation collisions collision key (NFD + lower case) on manifest and entries caseCollision, duplicateEntry
Truncated or corrupt container, bad checksum, base-256 size, data after the end marker strict reader malformedArchive
Tampered or forged signature, stripped signature see §7 signatureInvalid, signatureRequired
Archive swapped on the server, wrong size, oversized, plain-HTTP redirect SHA-256 and size from the index, streaming limit, URL policy archiveHashMismatch, sizeMismatch, downloadTooLarge, insecureURL
Index entry pointing at another pack id and version of the manifest must match the entry packMismatch
Crash or full disk during installation staging + journal + atomic rename; fault injection at every stage (recovered at launch)

After every rejected archive the tests assert that no pack is installed, that the staging area is empty and that no file exists outside the store.

# 9. Tooling (DataPipeline/packs/)

Python 3 standard library only, plus one Swift script because Ed25519 is not in the Python standard library.

text
python3 DataPipeline/packs/packtool.py validate <pack dir>...            # schema v1 + files on disk (hashes)
python3 DataPipeline/packs/packtool.py hash <pack dir> [--all] [--write] # recompute files[] and installedSize
python3 DataPipeline/packs/packtool.py announce-signature <pack dir> <key id>
python3 DataPipeline/packs/packtool.py build <pack dir> -o <archive> [--gzip]
python3 DataPipeline/packs/packtool.py index <archive>... -o index.json [--base-url URL] [--generated ISO]
swift   DataPipeline/packs/packsign.swift keygen|public|sign|verify …

packsign.swift keygen refuses to write a private key inside a git working tree and creates the file with mode 0600. Order: hash --write → announce-signature → packsign sign → build → index. A test runs this chain and installs the result with the library.

# 10. Limitations

  • No hosting exists. The index URL is a configuration value that is nil; the download path is tested against a loopback server only.
  • No trusted key exists. Until the owner generates a key pair and puts the public key in the application configuration, every pack is "unsigned – local/import" and nothing can be installed through the download path (by design). Key custody and rotation are owner decisions.
  • The pipeline packs core-ephemeris, missions, textures-starter, textures-hd and sky-imagery were aligned on schema v1 at the source (their generators write it; RepositoryPackTests reads them through PackStore as the bundled root and verifies their integrity). All five are localBuildOnly for now, by a conservative reading of the recorded licence statements (reasons in each manifest's redistributionNote): they cannot be exported or listed in an index until the owner decides.
  • Installation runs on the store actor: a multi-gigabyte install occupies it (cancellable, progress reported); two packs are not installed in parallel.
  • Durability against power loss relies on APFS ordering: file contents are fsynced, directory entries are not forced with F_FULLFSYNC. Crash injection in the tests is a simulated process death, not a power cut.
  • The archive carries no per-file compression other than whole-stream gzip; no delta updates.
  • .DS_Store files are skipped by directory import (and by the Python validator); any other unlisted file is an error.
  • Quotas count declared payload sizes; manifest.json and file-system overhead are not counted (reported by usage()).
Files main
Menu

Theme