Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dbe430659 |
@@ -103,8 +103,6 @@ func (v *Vaultik) FetchAndDecryptBlob(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// FetchBlob downloads a blob and returns a reader for the encrypted data.
|
// FetchBlob downloads a blob and returns a reader for the encrypted data.
|
||||||
// The reader is closed as soon as ctx is cancelled, which ends a read
|
|
||||||
// blocked inside it.
|
|
||||||
func (v *Vaultik) FetchBlob(
|
func (v *Vaultik) FetchBlob(
|
||||||
ctx context.Context, blobHash string,
|
ctx context.Context, blobHash string,
|
||||||
) (io.ReadCloser, error) {
|
) (io.ReadCloser, error) {
|
||||||
@@ -122,47 +120,5 @@ func (v *Vaultik) FetchBlob(
|
|||||||
return nil, fmt.Errorf("downloading blob %s: %w", shortHash(blobHash), err)
|
return nil, fmt.Errorf("downloading blob %s: %w", shortHash(blobHash), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return newCloseOnCancelReader(ctx, rc), nil
|
return rc, nil
|
||||||
}
|
|
||||||
|
|
||||||
// closeOnCancelReader closes the reader it wraps when ctx is cancelled.
|
|
||||||
// Not every backend's reader stops on cancel by itself (the file
|
|
||||||
// backend's does not), and a read stalled on a slow or hung source would
|
|
||||||
// otherwise outlast the shutdown timeout, so the process would exit
|
|
||||||
// before restore or deep verify removed its decrypted temporary files.
|
|
||||||
type closeOnCancelReader struct {
|
|
||||||
io.ReadCloser
|
|
||||||
|
|
||||||
ctx context.Context //nolint:containedctx // Read reports its error
|
|
||||||
stop func() bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newCloseOnCancelReader(
|
|
||||||
ctx context.Context, rc io.ReadCloser,
|
|
||||||
) *closeOnCancelReader {
|
|
||||||
return &closeOnCancelReader{
|
|
||||||
ReadCloser: rc,
|
|
||||||
ctx: ctx,
|
|
||||||
stop: context.AfterFunc(ctx, func() { _ = rc.Close() }),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read returns the context's error, not the closed reader's, once ctx
|
|
||||||
// has been cancelled.
|
|
||||||
func (r *closeOnCancelReader) Read(p []byte) (int, error) {
|
|
||||||
n, err := r.ReadCloser.Read(p)
|
|
||||||
if err != nil && r.ctx.Err() != nil {
|
|
||||||
return n, r.ctx.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes the wrapped reader, unless the cancel already closed it.
|
|
||||||
func (r *closeOnCancelReader) Close() error {
|
|
||||||
if !r.stop() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return r.ReadCloser.Close()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,13 +161,14 @@ func TestVerifyManifestBlobsRejectsShortHash(t *testing.T) {
|
|||||||
Blobs: []snapshot.BlobInfo{{Hash: "abc", CompressedSize: 1}},
|
Blobs: []snapshot.BlobInfo{{Hash: "abc", CompressedSize: 1}},
|
||||||
}
|
}
|
||||||
|
|
||||||
verified, missing, mismatched, missingSize, err :=
|
verified, missing, mismatched, missingSize, unchecked, err :=
|
||||||
v.verifyManifestBlobs(manifest, &VerifyOptions{JSON: true})
|
v.verifyManifestBlobs(manifest, &VerifyOptions{JSON: true})
|
||||||
require.ErrorIs(t, err, errInvalidBlobHash)
|
require.ErrorIs(t, err, errInvalidBlobHash)
|
||||||
require.Zero(t, verified)
|
require.Zero(t, verified)
|
||||||
require.Zero(t, missing)
|
require.Zero(t, missing)
|
||||||
require.Zero(t, mismatched)
|
require.Zero(t, mismatched)
|
||||||
require.Zero(t, missingSize)
|
require.Zero(t, missingSize)
|
||||||
|
require.Empty(t, unchecked)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestVerifyBlobChunksRejectsNegativeLength proves a blob_chunks row with a
|
// TestVerifyBlobChunksRejectsNegativeLength proves a blob_chunks row with a
|
||||||
|
|||||||
@@ -142,14 +142,14 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// scratchEntries returns the vaultik blob-cache and snapshot-database
|
// scratchEntries returns the vaultik blob-cache and snapshot-database
|
||||||
// scratch entries (restore's and deep verify's) currently present in dir.
|
// scratch entries currently present in dir.
|
||||||
func scratchEntries(t *testing.T, dir string) []string {
|
func scratchEntries(t *testing.T, dir string) []string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
var matches []string
|
var matches []string
|
||||||
|
|
||||||
for _, pattern := range []string{
|
for _, pattern := range []string{
|
||||||
"vaultik-blobcache-*", "vaultik-restore-*", "vaultik-verify-*",
|
"vaultik-blobcache-*", "vaultik-restore-*",
|
||||||
} {
|
} {
|
||||||
found, err := filepath.Glob(filepath.Join(dir, pattern))
|
found, err := filepath.Glob(filepath.Join(dir, pattern))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -206,119 +206,3 @@ func TestRestoreSkipErrorsCancelDuringBlobDownload(t *testing.T) {
|
|||||||
assert.NotContains(t, out.String(), srcPath,
|
assert.NotContains(t, out.String(), srcPath,
|
||||||
"the cancel was reported as a failed file")
|
"the cancel was reported as a failed file")
|
||||||
}
|
}
|
||||||
|
|
||||||
// stallingBlobStorer wraps a Storer so that every blob download hands
|
|
||||||
// over the first half of the blob and then stalls, ignoring the context,
|
|
||||||
// as a file:// blob on a hung USB stick or network share does. Only
|
|
||||||
// closing the returned reader ends the stall.
|
|
||||||
type stallingBlobStorer struct {
|
|
||||||
storage.Storer
|
|
||||||
|
|
||||||
once sync.Once
|
|
||||||
stalled chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newStallingBlobStorer(inner storage.Storer) *stallingBlobStorer {
|
|
||||||
return &stallingBlobStorer{Storer: inner, stalled: make(chan struct{})}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *stallingBlobStorer) Get(
|
|
||||||
ctx context.Context, key string,
|
|
||||||
) (io.ReadCloser, error) {
|
|
||||||
rc, err := s.Storer.Get(ctx, key)
|
|
||||||
if err != nil || !strings.HasPrefix(key, "blobs/") {
|
|
||||||
return rc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
blob, err := io.ReadAll(rc)
|
|
||||||
_ = rc.Close()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// The writer is never closed, so once the first half has been read
|
|
||||||
// the next Read blocks until the reader is closed.
|
|
||||||
pr, pw := io.Pipe()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
_, _ = pw.Write(blob[:len(blob)/2])
|
|
||||||
|
|
||||||
s.once.Do(func() { close(s.stalled) })
|
|
||||||
}()
|
|
||||||
|
|
||||||
return pr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestInterruptDuringStalledBlobReadCleansTempDir stops a restore and a
|
|
||||||
// deep verify while a blob read is stalled on a source that ignores the
|
|
||||||
// context. Stopping must end that read, so the operation unwinds and
|
|
||||||
// removes its decrypted scratch files well within the shutdown timeout
|
|
||||||
// (issue #325).
|
|
||||||
//
|
|
||||||
// Not parallel: it points TMPDIR at a private directory (via t.Setenv)
|
|
||||||
// so it can assert on exactly the scratch files the operation created.
|
|
||||||
func TestInterruptDuringStalledBlobReadCleansTempDir(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
|
|
||||||
operations := map[string]func(v *Vaultik, snapshotID, targetDir string) error{
|
|
||||||
"restore": func(v *Vaultik, snapshotID, targetDir string) error {
|
|
||||||
return v.Restore(&RestoreOptions{
|
|
||||||
SnapshotID: snapshotID,
|
|
||||||
TargetDir: targetDir,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
"deep verify": func(v *Vaultik, snapshotID, _ string) error {
|
|
||||||
return v.RunDeepVerify(snapshotID, &VerifyOptions{Deep: true})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, op := range operations {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
fs := afero.NewOsFs()
|
|
||||||
root := t.TempDir()
|
|
||||||
|
|
||||||
// Random content, so the blob stays large enough to stall
|
|
||||||
// part-way through its compressed, encrypted body.
|
|
||||||
cfg, storer, snapshotID, _ := backupOneFile(context.Background(),
|
|
||||||
t, fs, root, "a.bin", randomBytes(t, 256*1024), 0o644)
|
|
||||||
|
|
||||||
scratch := filepath.Join(root, "scratch")
|
|
||||||
require.NoError(t, fs.MkdirAll(scratch, 0o755))
|
|
||||||
t.Setenv("TMPDIR", scratch)
|
|
||||||
|
|
||||||
stalling := newStallingBlobStorer(storer)
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
v := newRestoreVaultik(ctx, cfg, stalling, fs)
|
|
||||||
v.cancel = cancel
|
|
||||||
|
|
||||||
var opErr error
|
|
||||||
|
|
||||||
stop := v.StartOperation(func() {
|
|
||||||
opErr = op(v, snapshotID, filepath.Join(root, "restored"))
|
|
||||||
})
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-stalling.stalled:
|
|
||||||
case <-time.After(30 * time.Second):
|
|
||||||
t.Fatal("the operation never reached a blob read")
|
|
||||||
}
|
|
||||||
|
|
||||||
require.NotEmpty(t, scratchEntries(t, scratch),
|
|
||||||
"expected decrypted scratch files to exist mid-read")
|
|
||||||
|
|
||||||
stopCtx, stopCancel := context.WithTimeout(
|
|
||||||
context.Background(), 10*time.Second)
|
|
||||||
defer stopCancel()
|
|
||||||
|
|
||||||
require.True(t, stop(stopCtx),
|
|
||||||
"stop timed out; the stalled blob read was not interrupted")
|
|
||||||
require.ErrorIs(t, opErr, context.Canceled)
|
|
||||||
require.Empty(t, scratchEntries(t, scratch),
|
|
||||||
"decrypted scratch files remained after the interrupt")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,15 +4,20 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/spf13/afero"
|
"github.com/spf13/afero"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"sneak.berlin/go/vaultik/internal/log"
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
"sneak.berlin/go/vaultik/internal/snapshot"
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
"sneak.berlin/go/vaultik/internal/ui"
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
)
|
)
|
||||||
@@ -151,6 +156,224 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) {
|
|||||||
"shallow verify must fail when db.zst.age is absent")
|
"shallow verify must fail when db.zst.age is absent")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// errStatDenied stands in for any storage error other than not-found: a
|
||||||
|
// permission error, an S3 403, a dropped connection.
|
||||||
|
var errStatDenied = errors.New("injected stat failure")
|
||||||
|
|
||||||
|
// statFailingStorer fails Stat with errStatDenied for the keys in
|
||||||
|
// failKeys and passes every other call to the wrapped Storer.
|
||||||
|
type statFailingStorer struct {
|
||||||
|
storage.Storer
|
||||||
|
|
||||||
|
failKeys []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s statFailingStorer) Stat(
|
||||||
|
ctx context.Context, key string,
|
||||||
|
) (*storage.ObjectInfo, error) {
|
||||||
|
if slices.Contains(s.failKeys, key) {
|
||||||
|
return nil, fmt.Errorf("stat %q: %w", key, errStatDenied)
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.Storer.Stat(ctx, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestShallowVerifyReportsStatErrorsApartFromMissing backs up a real
|
||||||
|
// snapshot, deletes one blob, and makes storage fail Stat with an error
|
||||||
|
// other than not-found for a second blob and for the encrypted database.
|
||||||
|
// Only the deleted blob may be counted as missing. The second blob and
|
||||||
|
// the database must be reported as could not be checked, with the error
|
||||||
|
// storage returned, and verify must fail, in the text output and under
|
||||||
|
// --json.
|
||||||
|
func TestShallowVerifyReportsStatErrorsApartFromMissing(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
fs := afero.NewOsFs()
|
||||||
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
chunkSize := int64(32 * 1024)
|
||||||
|
maxBlobSize := int64(128 * 1024)
|
||||||
|
|
||||||
|
// Random content, so the snapshot spans several blobs.
|
||||||
|
require.NoError(t, fs.MkdirAll(dataDir, 0o755))
|
||||||
|
appendRandomBytes(t, fs, map[string][]byte{},
|
||||||
|
filepath.Join(dataDir, "data.bin"), maxBlobSize*4)
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
cfg, storer, snapshotID := runFileStorageBackup(
|
||||||
|
ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize)
|
||||||
|
|
||||||
|
blobKeys := storedBlobKeys(t, storeDir)
|
||||||
|
require.GreaterOrEqual(t, len(blobKeys), 2, "expected at least two blobs")
|
||||||
|
|
||||||
|
missingKey, uncheckedKey := blobKeys[0], blobKeys[1]
|
||||||
|
missingHash, uncheckedHash := path.Base(missingKey), path.Base(uncheckedKey)
|
||||||
|
|
||||||
|
require.NoError(t, os.Remove(filepath.Join(storeDir, missingKey)))
|
||||||
|
|
||||||
|
dbKey := "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/db.zst.age"
|
||||||
|
failing := statFailingStorer{
|
||||||
|
Storer: storer,
|
||||||
|
failKeys: []string{uncheckedKey, dbKey},
|
||||||
|
}
|
||||||
|
|
||||||
|
newVerifier := func(out io.Writer) *vaultik.Vaultik {
|
||||||
|
v := &vaultik.Vaultik{
|
||||||
|
Config: cfg,
|
||||||
|
Storage: failing,
|
||||||
|
Fs: fs,
|
||||||
|
Stdout: out,
|
||||||
|
Stderr: io.Discard,
|
||||||
|
UI: ui.NewWithColor(io.Discard, false),
|
||||||
|
}
|
||||||
|
v.SetContext(ctx)
|
||||||
|
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
|
||||||
|
err := newVerifier(&out).VerifySnapshotWithOptions(
|
||||||
|
snapshotID, &vaultik.VerifyOptions{JSON: true})
|
||||||
|
require.Error(t, err)
|
||||||
|
|
||||||
|
result := decodeVerifyResult(t, out.Bytes())
|
||||||
|
require.Equal(t, "failed", result.Status)
|
||||||
|
require.Equal(t, 1, result.Missing, "only the deleted blob is missing")
|
||||||
|
require.Equal(t, result.BlobCount-2, result.Verified)
|
||||||
|
require.Len(t, result.Unchecked, 1)
|
||||||
|
require.Equal(t, uncheckedHash, result.Unchecked[0].Hash)
|
||||||
|
require.Contains(t, result.Unchecked[0].Error, errStatDenied.Error())
|
||||||
|
require.False(t, result.DatabaseMissing,
|
||||||
|
"a database that could not be checked is not missing")
|
||||||
|
require.Contains(t, result.DatabaseCheckError, errStatDenied.Error())
|
||||||
|
|
||||||
|
out.Reset()
|
||||||
|
err = newVerifier(&out).VerifySnapshotWithOptions(
|
||||||
|
snapshotID, &vaultik.VerifyOptions{})
|
||||||
|
require.Error(t, err)
|
||||||
|
|
||||||
|
text := out.String()
|
||||||
|
require.Contains(t, text, "Missing: "+missingHash)
|
||||||
|
require.NotContains(t, text, "Missing: "+uncheckedHash)
|
||||||
|
require.Contains(t, text, "Could not check: "+uncheckedHash)
|
||||||
|
require.Contains(t, text, "Encrypted database: could not be checked")
|
||||||
|
require.Contains(t, text, errStatDenied.Error())
|
||||||
|
require.Contains(t, text, "FAILED")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestShallowVerifyQuietFailsOnStatErrorAlone backs up a healthy snapshot,
|
||||||
|
// then makes storage fail Stat, with an error other than not-found, for
|
||||||
|
// one blob alone and then for the encrypted database alone. Each run must
|
||||||
|
// fail verify, and under --quiet, which drops the report, the error
|
||||||
|
// storage returned must still reach stderr.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // captureProcessStderr replaces os.Stderr
|
||||||
|
func TestShallowVerifyQuietFailsOnStatErrorAlone(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
|
||||||
|
fs := afero.NewOsFs()
|
||||||
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
chunkSize := int64(32 * 1024)
|
||||||
|
maxBlobSize := int64(128 * 1024)
|
||||||
|
|
||||||
|
require.NoError(t, fs.MkdirAll(dataDir, 0o755))
|
||||||
|
require.NoError(t, afero.WriteFile(fs,
|
||||||
|
filepath.Join(dataDir, "data.bin"),
|
||||||
|
bytesPattern("shallow-quiet-", int(maxBlobSize*2)), 0o644))
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
cfg, storer, snapshotID := runFileStorageBackup(
|
||||||
|
ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize)
|
||||||
|
|
||||||
|
newQuietVerifier := func(s storage.Storer) *vaultik.Vaultik {
|
||||||
|
v := &vaultik.Vaultik{
|
||||||
|
Config: cfg,
|
||||||
|
Storage: s,
|
||||||
|
Fs: fs,
|
||||||
|
Stdout: io.Discard,
|
||||||
|
Stderr: io.Discard,
|
||||||
|
UI: ui.NewWithColor(io.Discard, false),
|
||||||
|
}
|
||||||
|
v.SetContext(ctx)
|
||||||
|
v.UI.SetQuiet(true)
|
||||||
|
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
require.NoError(t,
|
||||||
|
newQuietVerifier(storer).VerifySnapshotWithOptions(
|
||||||
|
snapshotID, &vaultik.VerifyOptions{}),
|
||||||
|
"shallow verify should pass on a healthy snapshot")
|
||||||
|
|
||||||
|
blobKeys := storedBlobKeys(t, storeDir)
|
||||||
|
require.NotEmpty(t, blobKeys)
|
||||||
|
|
||||||
|
dbKey := "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/db.zst.age"
|
||||||
|
|
||||||
|
for _, failKey := range []string{blobKeys[0], dbKey} {
|
||||||
|
v := newQuietVerifier(statFailingStorer{
|
||||||
|
Storer: storer,
|
||||||
|
failKeys: []string{failKey},
|
||||||
|
})
|
||||||
|
|
||||||
|
var err error
|
||||||
|
|
||||||
|
stderr := captureProcessStderr(t, func() {
|
||||||
|
err = v.VerifySnapshotWithOptions(
|
||||||
|
snapshotID, &vaultik.VerifyOptions{})
|
||||||
|
})
|
||||||
|
|
||||||
|
require.Error(t, err,
|
||||||
|
"verify must fail when %s could not be checked", failKey)
|
||||||
|
require.Contains(t, stderr, errStatDenied.Error(),
|
||||||
|
"under --quiet the error for %s must still reach stderr", failKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// storedBlobKeys returns the storage key of every blob file under
|
||||||
|
// storeDir, sorted.
|
||||||
|
func storedBlobKeys(t *testing.T, storeDir string) []string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
var keys []string
|
||||||
|
|
||||||
|
err := filepath.Walk(filepath.Join(storeDir, "blobs"),
|
||||||
|
func(p string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rel, err := filepath.Rel(storeDir, p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
keys = append(keys, filepath.ToSlash(rel))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
// growOneBlob appends bytes to the first blob file found under blobsDir,
|
// growOneBlob appends bytes to the first blob file found under blobsDir,
|
||||||
// changing its on-disk size so it no longer matches the manifest.
|
// changing its on-disk size so it no longer matches the manifest.
|
||||||
func growOneBlob(t *testing.T, fs afero.Fs, blobsDir string) {
|
func growOneBlob(t *testing.T, fs afero.Fs, blobsDir string) {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
|
|
||||||
"sneak.berlin/go/vaultik/internal/log"
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
"sneak.berlin/go/vaultik/internal/snapshot"
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
"sneak.berlin/go/vaultik/internal/types"
|
"sneak.berlin/go/vaultik/internal/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -774,18 +775,10 @@ func (v *Vaultik) VerifySnapshotWithOptions(
|
|||||||
v.stdoutf("Checking blob presence and sizes...\n")
|
v.stdoutf("Checking blob presence and sizes...\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
// A snapshot is only restorable if its encrypted database is present
|
v.checkSnapshotDatabase(remoteKey, result)
|
||||||
// alongside the blobs. Shallow verify checks that the object exists; it
|
|
||||||
// does not decrypt it (that is deep verify's job).
|
|
||||||
dbPath := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey)
|
|
||||||
|
|
||||||
_, dbErr := v.Storage.Stat(v.ctx, dbPath)
|
result.Verified, result.Missing, result.Mismatched, result.MissingSize,
|
||||||
if dbErr != nil {
|
result.Unchecked, err = v.verifyManifestBlobs(manifest, opts)
|
||||||
result.DatabaseMissing = true
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Verified, result.Missing, result.Mismatched, result.MissingSize, err =
|
|
||||||
v.verifyManifestBlobs(manifest, opts)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if opts.JSON {
|
if opts.JSON {
|
||||||
result.Status = verifyStatusFailed
|
result.Status = verifyStatusFailed
|
||||||
@@ -822,25 +815,46 @@ func (v *Vaultik) printVerifyHeader(snapshotID string, opts *VerifyOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkSnapshotDatabase records in result whether the snapshot's
|
||||||
|
// encrypted database is missing or could not be checked. A snapshot is
|
||||||
|
// only restorable if its database is present alongside the blobs.
|
||||||
|
// Shallow verify checks that the object exists; it does not decrypt it
|
||||||
|
// (that is deep verify's job).
|
||||||
|
func (v *Vaultik) checkSnapshotDatabase(remoteKey string, result *VerifyResult) {
|
||||||
|
dbPath := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey)
|
||||||
|
|
||||||
|
_, err := v.Storage.Stat(v.ctx, dbPath)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, storage.ErrNotFound):
|
||||||
|
result.DatabaseMissing = true
|
||||||
|
case err != nil:
|
||||||
|
result.DatabaseCheckError = err.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// verifyManifestBlobs checks that each blob in the manifest is present in
|
// verifyManifestBlobs checks that each blob in the manifest is present in
|
||||||
// storage with the size the manifest records, returning the counts of
|
// storage with the size the manifest records, returning the counts of
|
||||||
// blobs that were present with the right size, absent, and present but the
|
// blobs that were present with the right size, absent, and present but the
|
||||||
// wrong size, plus the total bytes of the absent blobs. It does not read
|
// wrong size, the total bytes of the absent blobs, and the blobs it could
|
||||||
// blob contents; deep verification (RunDeepVerify) does that. The size
|
// not check because storage returned an error other than not-found. It
|
||||||
// comparison matches the deep path (see verifyBlobExistenceFromDB).
|
// does not read blob contents; deep verification (RunDeepVerify) does
|
||||||
|
// that. The size comparison matches the deep path (see
|
||||||
|
// verifyBlobExistenceFromDB).
|
||||||
func (v *Vaultik) verifyManifestBlobs(
|
func (v *Vaultik) verifyManifestBlobs(
|
||||||
manifest *snapshot.Manifest, opts *VerifyOptions,
|
manifest *snapshot.Manifest, opts *VerifyOptions,
|
||||||
) (int, int, int, int64, error) {
|
) (int, int, int, int64, []UncheckedBlob, error) {
|
||||||
var (
|
var (
|
||||||
verified, missing, mismatched int
|
verified, missing, mismatched int
|
||||||
missingSize int64
|
missingSize int64
|
||||||
|
unchecked []UncheckedBlob
|
||||||
)
|
)
|
||||||
|
|
||||||
for _, blob := range manifest.Blobs {
|
for _, blob := range manifest.Blobs {
|
||||||
// The manifest is unauthenticated, so its blob hashes are checked
|
// The manifest is unauthenticated, so its blob hashes are checked
|
||||||
// before being spliced into a storage path.
|
// before being spliced into a storage path.
|
||||||
if !isBlobHash(blob.Hash) {
|
if !isBlobHash(blob.Hash) {
|
||||||
return 0, 0, 0, 0, fmt.Errorf("%w: %s",
|
return 0, 0, 0, 0, nil, fmt.Errorf("%w: %s",
|
||||||
errInvalidBlobHash, shortHash(blob.Hash))
|
errInvalidBlobHash, shortHash(blob.Hash))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -849,7 +863,7 @@ func (v *Vaultik) verifyManifestBlobs(
|
|||||||
|
|
||||||
stat, err := v.Storage.Stat(v.ctx, blobPath)
|
stat, err := v.Storage.Stat(v.ctx, blobPath)
|
||||||
switch {
|
switch {
|
||||||
case err != nil:
|
case errors.Is(err, storage.ErrNotFound):
|
||||||
if !opts.JSON && !v.UI.Quiet() {
|
if !opts.JSON && !v.UI.Quiet() {
|
||||||
v.stdoutf(" Missing: %s (%s)\n",
|
v.stdoutf(" Missing: %s (%s)\n",
|
||||||
blob.Hash, ubytes(blob.CompressedSize))
|
blob.Hash, ubytes(blob.CompressedSize))
|
||||||
@@ -857,6 +871,13 @@ func (v *Vaultik) verifyManifestBlobs(
|
|||||||
|
|
||||||
missing++
|
missing++
|
||||||
missingSize += blob.CompressedSize
|
missingSize += blob.CompressedSize
|
||||||
|
case err != nil:
|
||||||
|
if !opts.JSON && !v.UI.Quiet() {
|
||||||
|
v.stdoutf(" Could not check: %s (%v)\n", blob.Hash, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
unchecked = append(unchecked,
|
||||||
|
UncheckedBlob{Hash: blob.Hash, Error: err.Error()})
|
||||||
case stat.Size != blob.CompressedSize:
|
case stat.Size != blob.CompressedSize:
|
||||||
if !opts.JSON && !v.UI.Quiet() {
|
if !opts.JSON && !v.UI.Quiet() {
|
||||||
v.stdoutf(" Wrong size: %s (store has %s, manifest lists %s)\n",
|
v.stdoutf(" Wrong size: %s (store has %s, manifest lists %s)\n",
|
||||||
@@ -869,7 +890,7 @@ func (v *Vaultik) verifyManifestBlobs(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return verified, missing, mismatched, missingSize, nil
|
return verified, missing, mismatched, missingSize, unchecked, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatVerifyResult outputs the final verification results as JSON or
|
// formatVerifyResult outputs the final verification results as JSON or
|
||||||
@@ -890,9 +911,19 @@ func (v *Vaultik) formatVerifyResult(
|
|||||||
return v.outputVerifyJSON(result)
|
return v.outputVerifyJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Under --quiet a failure is still returned, and the cli layer
|
// --quiet drops the report but not the errors storage returned, which
|
||||||
// prints it on stderr.
|
// are logged on stderr. A failure is still returned either way, and
|
||||||
if !v.UI.Quiet() {
|
// the cli layer prints it on stderr.
|
||||||
|
if v.UI.Quiet() {
|
||||||
|
for _, blob := range result.Unchecked {
|
||||||
|
log.Warn("Could not check blob", "blob", blob.Hash, "error", blob.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
if result.DatabaseCheckError != "" {
|
||||||
|
log.Warn("Could not check the encrypted database",
|
||||||
|
"snapshot", result.SnapshotID, "error", result.DatabaseCheckError)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
v.printVerifySummary(result, failure)
|
v.printVerifySummary(result, failure)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -918,10 +949,19 @@ func (v *Vaultik) printVerifySummary(result *VerifyResult, failure string) {
|
|||||||
v.stdoutf(" Wrong size: %d blobs\n", result.Mismatched)
|
v.stdoutf(" Wrong size: %d blobs\n", result.Mismatched)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(result.Unchecked) > 0 {
|
||||||
|
v.stdoutf(" Could not check: %d blobs\n", len(result.Unchecked))
|
||||||
|
}
|
||||||
|
|
||||||
if result.DatabaseMissing {
|
if result.DatabaseMissing {
|
||||||
v.stdoutf(" Encrypted database: missing\n")
|
v.stdoutf(" Encrypted database: missing\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if result.DatabaseCheckError != "" {
|
||||||
|
v.stdoutf(" Encrypted database: could not be checked (%s)\n",
|
||||||
|
result.DatabaseCheckError)
|
||||||
|
}
|
||||||
|
|
||||||
v.stdoutf(" Status: ")
|
v.stdoutf(" Status: ")
|
||||||
|
|
||||||
if failure != "" {
|
if failure != "" {
|
||||||
@@ -949,10 +989,19 @@ func shallowVerifyFailure(result *VerifyResult) string {
|
|||||||
fmt.Sprintf("%d blobs have the wrong size", result.Mismatched))
|
fmt.Sprintf("%d blobs have the wrong size", result.Mismatched))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(result.Unchecked) > 0 {
|
||||||
|
parts = append(parts, fmt.Sprintf("%d blobs could not be checked",
|
||||||
|
len(result.Unchecked)))
|
||||||
|
}
|
||||||
|
|
||||||
if result.DatabaseMissing {
|
if result.DatabaseMissing {
|
||||||
parts = append(parts, "the encrypted database is missing")
|
parts = append(parts, "the encrypted database is missing")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if result.DatabaseCheckError != "" {
|
||||||
|
parts = append(parts, "the encrypted database could not be checked")
|
||||||
|
}
|
||||||
|
|
||||||
return strings.Join(parts, "; ")
|
return strings.Join(parts, "; ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -57,13 +57,27 @@ type VerifyResult struct {
|
|||||||
Missing int `json:"missing"`
|
Missing int `json:"missing"`
|
||||||
MissingSize int64 `json:"missing_size,omitempty"`
|
MissingSize int64 `json:"missing_size,omitempty"`
|
||||||
Mismatched int `json:"mismatched,omitempty"`
|
Mismatched int `json:"mismatched,omitempty"`
|
||||||
|
// Unchecked lists the blobs shallow verify could not check, because
|
||||||
|
// storage answered with an error other than not-found, so whether
|
||||||
|
// they are present is unknown.
|
||||||
|
Unchecked []UncheckedBlob `json:"unchecked,omitempty"`
|
||||||
// DatabaseMissing is set by shallow verify when the snapshot's
|
// DatabaseMissing is set by shallow verify when the snapshot's
|
||||||
// encrypted database (metadata/<key>/db.zst.age) is absent, which
|
// encrypted database (metadata/<key>/db.zst.age) is absent, which
|
||||||
// makes the snapshot unrestorable regardless of the blobs.
|
// makes the snapshot unrestorable regardless of the blobs.
|
||||||
DatabaseMissing bool `json:"database_missing,omitempty"`
|
DatabaseMissing bool `json:"database_missing,omitempty"`
|
||||||
|
// DatabaseCheckError is set by shallow verify to the error storage
|
||||||
|
// returned when the encrypted database could not be checked.
|
||||||
|
DatabaseCheckError string `json:"database_check_error,omitempty"`
|
||||||
ErrorMessage string `json:"error,omitempty"`
|
ErrorMessage string `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UncheckedBlob is a blob shallow verify could not check, with the error
|
||||||
|
// storage returned for it.
|
||||||
|
type UncheckedBlob struct {
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
// deepVerifyFailure records a failure in the result and returns it appropriately
|
// deepVerifyFailure records a failure in the result and returns it appropriately
|
||||||
func (v *Vaultik) deepVerifyFailure(
|
func (v *Vaultik) deepVerifyFailure(
|
||||||
result *VerifyResult, opts *VerifyOptions, msg string, err error,
|
result *VerifyResult, opts *VerifyOptions, msg string, err error,
|
||||||
|
|||||||
Reference in New Issue
Block a user