// Package archive is the files archive of the move-any-app design §8: a // deterministic tar of an instance's files directory and its .env, // compressed with zstd, then sealed under the deployment's config keypair. // // The source box builds and seals it; the target box opens, verifies and // extracts it. The target treats every archive as hostile. The config // public key is widely held, so anyone who can write the staging bucket can // seal an archive that opens: authentication proves who it was sealed for, // not who sealed it. Every limit Build obeys, Verify and Extract enforce // again, and Build obeys every limit Verify and Extract enforce, so an // archive Build wrote always lands. package archive import ( "archive/tar" "crypto/sha256" "encoding/hex" "errors" "fmt" "hash" "io" "io/fs" "os" "path/filepath" "sort" "github.com/klauspost/compress/zstd" ) // ManifestVersion is the Manifest.V this package writes and reads. const ManifestVersion = 1 // Errors from Build (ErrSpecialFile, ErrOverCap, ErrTooManyEntries, // ErrChanged and the long-path ErrBadPath) reach the operator through the // source report's S1; their texts are rows MV-N77 to MV-N81 and MV-N86 of // the copy record. The rest are the target's refusals. var ( ErrSpecialFile = errors.New("archive: only regular files and directories move") ErrOverCap = errors.New("archive: the files directory is over 256 MiB") ErrTooManyEntries = fmt.Errorf("archive: the files directory holds more than %d entries", MaxEntries) ErrChanged = errors.New("archive: a file changed while it was being archived") ErrBadPath = errors.New("archive: refused path") ErrTooLarge = errors.New("archive: the decoded archive is over its size limit") ErrNotEmpty = errors.New("archive: the destination files directory is not empty") // ErrPastTreeCap is Build's refusal of a path longer than TreePathLen // (hostfiles' cap) but within MaxPathLen; the source says MV-N502. ErrPastTreeCap = errors.New("archive: a path is past the files tree's length cap") ) // PathError is a Build refusal that names a file: Err is the sentinel // (errors.Is sees it), Path the file as Build names it (relative to the // files directory, or the env file's base name). It lets a caller say // which file in its own words without reading the error's text; Error() is // the text the sentinel's rows record (MV-N77, MV-N80, MV-N81, MV-N86). type PathError struct { Err error Path string msg string } func (e *PathError) Error() string { if e.msg != "" { return e.msg } return e.Err.Error() + ": " + e.Path } func (e *PathError) Unwrap() error { return e.Err } // The refusals that name a file, each one whole recorded sentence (copy // record MV-N77, MV-N80, MV-N81 and MV-N86) so the copy gate can read it. // Err is the sentinel errors.Is sees; the text is the sentinel's, a colon // and the path, as the rows say. func specialFileError(path string) error { return &PathError{Err: ErrSpecialFile, Path: path, msg: fmt.Sprintf("archive: only regular files and directories move: %s", path)} } func hardLinkError(path string) error { return &PathError{Err: ErrSpecialFile, Path: path, msg: fmt.Sprintf("archive: only regular files and directories move: %s is a hard link", path)} } func changedError(path string) error { return &PathError{Err: ErrChanged, Path: path, msg: fmt.Sprintf("archive: a file changed while it was being archived: %s", path)} } // The row says 4096, so the sentence does; this fails to compile if // MaxPathLen is ever changed without the row. const _ = uint(MaxPathLen-4096) + uint(4096-MaxPathLen) // treePathError is a path past TreePathLen but within MaxPathLen: the // archive format could carry it, the target's files manifest could not. // The operator's sentence is the caller's (MV-N502, from the sentinel); // this text reaches the log only. func treePathError(path string) error { return &PathError{Err: ErrPastTreeCap, Path: path, msg: fmt.Sprintf("archive: refused path: %s is longer than the files tree's %d-byte cap", path, TreePathLen)} } func longPathError(path string) error { return &PathError{Err: ErrBadPath, Path: path, msg: fmt.Sprintf("archive: refused path: %s is longer than 4096 bytes", path)} } // The limits as enforced. Variables only so tests can lower them; nothing // else writes them. var ( entryLimit = MaxEntries decodedLimit = MaxDecoded ) // Entry is one regular file in the manifest: its archive path ("env" or // "files/"), size and sha256. type Entry struct { Path string `json:"path"` Size int64 `json:"size"` SHA256 string `json:"sha256"` } // Manifest travels beside the sealed object (§8.2). SealedDataKey is the // archive's data key sealed to the deployment's config keypair (a v2 // envelope bound to the app); it is not an object key (F29). type Manifest struct { V int `json:"v"` Op string `json:"op"` Incarnation string `json:"incarnation"` Plain string `json:"plain"` Sealed string `json:"sealed"` Bytes int64 `json:"bytes"` Entries []Entry `json:"entries"` SealedDataKey string `json:"sealed_data_key"` Chunk int `json:"chunk"` } // item is one listed entry: its archive name, where to open it, and its // Lstat at listing time, which the open must match. type item struct { name string // "env", "files/" rel string // path inside the files root; "" for env root *os.Root // the files root; nil for env path string // envPath, for env info fs.FileInfo // as listed } // walk lists the files directory and envPath in archive order, refusing // anything that is not a regular file or a directory and excluding the // marker. The files directory is read through an os.Root, so nothing a // tenant does inside it (a directory swapped for a symlink mid-walk) can // make the walk or a later open leave it. // // skip, when non-nil, is asked each path relative to the files directory // (slash-separated, as the archive names it) before anything else is read // about it: a path it accepts is left out as the marker is, a directory // with everything under it, and is neither typed nor counted, so a // platform artifact of any kind (a socket, a FIFO) cannot fail the walk. // envPath is never asked. func walk(root *os.Root, envPath string, skip func(rel string) bool) ([]item, error) { var items []item add := func(it item) error { if len(items) >= entryLimit { return ErrTooManyEntries } items = append(items, it) return nil } if root != nil { err := fs.WalkDir(root.FS(), ".", func(p string, d fs.DirEntry, err error) error { if err != nil { return err } if p == "." { return nil } if p == MarkerName || (skip != nil && skip(p)) { // The marker is never archived, nor anything under it if // it is (wrongly) a directory; nor is a path the caller // skips. if d.IsDir() { return fs.SkipDir } return nil } // Through the root only (census ruling moves-overcap-cut-236, // binding): a read that fails refuses the walk, never a retry by // path. info, err := root.Lstat(p) if err != nil { return err } if !info.Mode().IsRegular() && !info.IsDir() { return specialFileError(p) } if len(p) > MaxPathLen { return longPathError(p) } if len(p) > TreePathLen { return treePathError(p) } return add(item{name: FilesPrefix + p, rel: p, root: root, info: info}) }) if err != nil { return nil, err } } if envPath != "" { info, err := os.Lstat(envPath) switch { case errors.Is(err, fs.ErrNotExist): case err != nil: return nil, err case !info.Mode().IsRegular(): return nil, specialFileError(filepath.Base(envPath)) default: if err := add(item{name: EnvEntry, path: envPath, info: info}); err != nil { return nil, err } } } sort.Slice(items, func(i, j int) bool { return items[i].name < items[j].name }) return items, nil } // openItem opens a listed regular file. A variable so a test can stand in // a file that grows after it was listed. var openItem = openItemChecked // openItemChecked opens it.rel inside the files root (or the env path) and // requires the opened file to be the one listed: a regular file with the // listed identity and one name. A file swapped after the walk (for a FIFO, another file, // or a symlink the root would refuse to leave by) fails here. The open is // non-blocking where the platform has the flag, so a swapped-in FIFO // returns at once instead of waiting for a writer. func openItemChecked(it item) (io.ReadCloser, error) { var f *os.File var err error if it.root != nil { f, err = it.root.OpenFile(it.rel, os.O_RDONLY|openNonblock, 0) } else { f, err = os.OpenFile(it.path, os.O_RDONLY|openNonblock, 0) } if err != nil { return nil, err } got, err := f.Stat() if err != nil { f.Close() return nil, err } if !got.Mode().IsRegular() || !os.SameFile(it.info, got) { f.Close() return nil, changedError(displayName(it)) } // Phase 1 does not carry hard links. os.Root constrains names, not // inodes: a pre-existing link to a file outside the instance directory // is a regular file with the listed identity, and reading it would // carry the outside inode to the target. Counted on the opened file. if linkCount(got) > 1 { f.Close() return nil, hardLinkError(displayName(it)) } return f, nil } func displayName(it item) string { if it.root == nil { return filepath.Base(it.path) } return it.rel } // hashWriter hashes and counts the tar stream on its way to the // compressor. It enforces no limit: content is capped where sizes are // admitted, and the stream's length follows from the entry limits. type hashWriter struct { w io.Writer h hash.Hash n int64 } func (c *hashWriter) Write(p []byte) (int, error) { c.h.Write(p) c.n += int64(len(p)) return c.w.Write(p) } func digestString(h hash.Hash) string { return "sha256:" + hex.EncodeToString(h.Sum(nil)) } // built is one pass over the tree. type built struct { plain string entries []Entry content int64 tarBytes int64 count int // tar entries: files, directories and env } // openFilesRoot opens filesDir as an os.Root, requiring it to be a real // directory (not a symlink to one) at both the Lstat and the open. A // missing directory is an empty one: the archive then carries env only. func openFilesRoot(filesDir string) (*os.Root, error) { if filesDir == "" { return nil, errors.New("archive: no files directory named") } info, err := os.Lstat(filesDir) if errors.Is(err, fs.ErrNotExist) { return nil, nil } if err != nil { return nil, err } if !info.IsDir() { // The files root itself is not a directory: untyped, so the caller // reports it as the files failing to archive, never as a . return nil, fmt.Errorf("%w: %s", ErrSpecialFile, filesDir) } root, err := os.OpenRoot(filesDir) if err != nil { return nil, err } got, err := root.Stat(".") if err != nil { root.Close() return nil, err } if !os.SameFile(info, got) { root.Close() // The root itself, not a file in it: untyped, as above. return nil, fmt.Errorf("%w: %s", ErrChanged, filesDir) } return root, nil } // build writes the tar of filesDir and envPath to out and returns what // Build and PlainDigest report. func build(filesDir, envPath string, out io.Writer) (built, error) { return buildFiltered(filesDir, envPath, nil, out) } // buildFiltered is build over the paths skip leaves in (walk). func buildFiltered(filesDir, envPath string, skip func(rel string) bool, out io.Writer) (built, error) { root, err := openFilesRoot(filesDir) if err != nil { return built{}, err } if root != nil { defer root.Close() } items, err := walk(root, envPath, skip) if err != nil { return built{}, err } var b built hw := &hashWriter{w: out, h: sha256.New()} tw := tar.NewWriter(hw) for _, it := range items { hdr := &tar.Header{Name: it.name, Mode: int64(it.info.Mode().Perm()), Format: tar.FormatPAX} if it.info.IsDir() { hdr.Typeflag = tar.TypeDir hdr.Name += "/" } else { hdr.Typeflag = tar.TypeReg hdr.Size = it.info.Size() // Admitted against the cap before the header commits the size. if hdr.Size > Cap-b.content { return built{}, ErrOverCap } b.content += hdr.Size } if err := tw.WriteHeader(hdr); err != nil { return built{}, err } b.count++ if hdr.Typeflag != tar.TypeReg { continue } e, err := copyItem(tw, it, hdr.Size) if err != nil { return built{}, err } b.entries = append(b.entries, e) } if err := tw.Close(); err != nil { return built{}, err } b.plain, b.tarBytes = digestString(hw.h), hw.n return b, nil } // copyItem streams exactly the admitted size of one file into the tar. // This is the cap while streaming: a file is never read past the size its // header committed (and the cap admitted), so a file that grows after it // was listed cannot carry the archive past Cap. It is refused as changed, // as is one that shrank, rather than archived torn. func copyItem(tw io.Writer, it item, size int64) (Entry, error) { rc, err := openItem(it) if err != nil { return Entry{}, err } defer rc.Close() fh := sha256.New() n, err := io.CopyN(io.MultiWriter(tw, fh), rc, size) if errors.Is(err, io.EOF) { return Entry{}, changedError(displayName(it)) } if err != nil { return Entry{}, err } var one [1]byte m, err := io.ReadFull(rc, one[:]) if m > 0 { return Entry{}, changedError(displayName(it)) } if err != io.EOF { return Entry{}, err } return Entry{Path: it.name, Size: n, SHA256: digestString(fh)}, nil } // Build writes the archive (tar then zstd) to w and returns the plaintext // digest (of the tar stream), the regular-file entries and the content // byte count. Owners and times are zeroed, modes kept, so equal content // gives equal plaintext (§8.1). The files directory's entries live under // "files/" and .env is "env", in separate namespaces, so an // application file or directory named "env" is carried as "files/env" and // can never collide with the overlay. A missing envPath (or "") means the // archive has no env entry; a missing filesDir is an empty one. func Build(filesDir, envPath string, w io.Writer) (plain string, entries []Entry, bytes int64, err error) { return BuildFiltered(filesDir, envPath, nil, w) } // BuildFiltered is Build over the files directory without the paths skip // accepts. skip is asked each path relative to filesDir, slash-separated // (a top-level entry is its bare name); a skipped directory is skipped // whole, and a skipped entry of any type is never read, typed or counted. // The env entry is never asked. A nil skip is Build. Nothing calls it with // a filter today: the offline move's sealer archives a nested instance's // files directory (/, which holds nothing of the // platform's but the marker) with Build, and refuses the seal over any // entry of the app's beside it. func BuildFiltered(filesDir, envPath string, skip func(rel string) bool, w io.Writer) (plain string, entries []Entry, bytes int64, err error) { zw, err := zstd.NewWriter(w, zstd.WithEncoderConcurrency(1), zstd.WithWindowSize(zstdWindow)) if err != nil { return "", nil, 0, err } b, err := buildFiltered(filesDir, envPath, skip, zw) if err != nil { zw.Close() return "", nil, 0, err } if err := zw.Close(); err != nil { return "", nil, 0, err } return b.plain, b.entries, b.content, nil } // PlainDigest runs Build's walk and tar without compressing or writing // anything, and returns the same plaintext digest Build would, the content // byte count and the number of regular-file entries (env included). It is // the baseline the source records at `stopped` before any archive exists // (§8.3), and the comparison every recovery makes. func PlainDigest(filesDir, envPath string) (plain string, bytes int64, entries int, err error) { b, err := build(filesDir, envPath, io.Discard) if err != nil { return "", 0, 0, err } return b.plain, b.content, len(b.entries), nil }