Compare commits
3 Commits
fix/sql-in
...
2aac1df53b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2aac1df53b | ||
| 71f4cb9028 | |||
|
|
24539ced5b |
@@ -1,64 +0,0 @@
|
|||||||
package blobgen
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/rand"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// testRecipient is a static age recipient for tests.
|
|
||||||
const testRecipient = "age1cplgrwj77ta54dnmydvvmzn64ltk83ankxl5sww04mrtmu62kv3s89gmvv"
|
|
||||||
|
|
||||||
// TestCompressStreamNoDoubleClose is a regression test for issue #28.
|
|
||||||
// It verifies that CompressStream does not panic or return an error due to
|
|
||||||
// double-closing the underlying blobgen.Writer. Before the fix in PR #33,
|
|
||||||
// the explicit Close() on the happy path combined with defer Close() would
|
|
||||||
// cause a double close.
|
|
||||||
func TestCompressStreamNoDoubleClose(t *testing.T) {
|
|
||||||
input := []byte("regression test data for issue #28 double-close fix")
|
|
||||||
var buf bytes.Buffer
|
|
||||||
|
|
||||||
written, hash, err := CompressStream(&buf, bytes.NewReader(input), 3, []string{testRecipient})
|
|
||||||
require.NoError(t, err, "CompressStream should not return an error")
|
|
||||||
assert.True(t, written > 0, "expected bytes written > 0")
|
|
||||||
assert.NotEmpty(t, hash, "expected non-empty hash")
|
|
||||||
assert.True(t, buf.Len() > 0, "expected non-empty output")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestCompressStreamLargeInput exercises CompressStream with a larger payload
|
|
||||||
// to ensure no double-close issues surface under heavier I/O.
|
|
||||||
func TestCompressStreamLargeInput(t *testing.T) {
|
|
||||||
data := make([]byte, 512*1024) // 512 KB
|
|
||||||
_, err := rand.Read(data)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
var buf bytes.Buffer
|
|
||||||
written, hash, err := CompressStream(&buf, bytes.NewReader(data), 3, []string{testRecipient})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.True(t, written > 0)
|
|
||||||
assert.NotEmpty(t, hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestCompressStreamEmptyInput verifies CompressStream handles empty input
|
|
||||||
// without double-close issues.
|
|
||||||
func TestCompressStreamEmptyInput(t *testing.T) {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
_, hash, err := CompressStream(&buf, strings.NewReader(""), 3, []string{testRecipient})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.NotEmpty(t, hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestCompressDataNoDoubleClose mirrors the stream test for CompressData,
|
|
||||||
// ensuring the explicit Close + error-path Close pattern is also safe.
|
|
||||||
func TestCompressDataNoDoubleClose(t *testing.T) {
|
|
||||||
input := []byte("CompressData regression test for double-close")
|
|
||||||
result, err := CompressData(input, 3, []string{testRecipient})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.True(t, result.CompressedSize > 0)
|
|
||||||
assert.True(t, result.UncompressedSize == int64(len(input)))
|
|
||||||
assert.NotEmpty(t, result.SHA256)
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
package vaultik
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"filippo.io/age"
|
|
||||||
"git.eeqj.de/sneak/vaultik/internal/blobgen"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FetchAndDecryptBlobResult holds the result of fetching and decrypting a blob.
|
|
||||||
type FetchAndDecryptBlobResult struct {
|
|
||||||
Data []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// FetchAndDecryptBlob downloads a blob, decrypts it, and returns the plaintext data.
|
|
||||||
func (v *Vaultik) FetchAndDecryptBlob(ctx context.Context, blobHash string, expectedSize int64, identity age.Identity) (*FetchAndDecryptBlobResult, error) {
|
|
||||||
rc, _, err := v.FetchBlob(ctx, blobHash, expectedSize)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer func() { _ = rc.Close() }()
|
|
||||||
|
|
||||||
reader, err := blobgen.NewReader(rc, identity)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("creating blob reader: %w", err)
|
|
||||||
}
|
|
||||||
defer func() { _ = reader.Close() }()
|
|
||||||
|
|
||||||
data, err := io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("reading blob data: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &FetchAndDecryptBlobResult{Data: data}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// FetchBlob downloads a blob and returns a reader for the encrypted data.
|
|
||||||
func (v *Vaultik) FetchBlob(ctx context.Context, blobHash string, expectedSize int64) (io.ReadCloser, int64, error) {
|
|
||||||
blobPath := fmt.Sprintf("blobs/%s/%s/%s", blobHash[:2], blobHash[2:4], blobHash)
|
|
||||||
|
|
||||||
rc, err := v.Storage.Get(ctx, blobPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, fmt.Errorf("downloading blob %s: %w", blobHash[:16], err)
|
|
||||||
}
|
|
||||||
|
|
||||||
info, err := v.Storage.Stat(ctx, blobPath)
|
|
||||||
if err != nil {
|
|
||||||
_ = rc.Close()
|
|
||||||
return nil, 0, fmt.Errorf("stat blob %s: %w", blobHash[:16], err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return rc, info.Size, nil
|
|
||||||
}
|
|
||||||
@@ -1,207 +0,0 @@
|
|||||||
package vaultik
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// blobDiskCacheEntry tracks a cached blob on disk.
|
|
||||||
type blobDiskCacheEntry struct {
|
|
||||||
key string
|
|
||||||
size int64
|
|
||||||
prev *blobDiskCacheEntry
|
|
||||||
next *blobDiskCacheEntry
|
|
||||||
}
|
|
||||||
|
|
||||||
// blobDiskCache is an LRU cache that stores blobs on disk instead of in memory.
|
|
||||||
// Blobs are written to a temp directory keyed by their hash. When total size
|
|
||||||
// exceeds maxBytes, the least-recently-used entries are evicted (deleted from disk).
|
|
||||||
type blobDiskCache struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
dir string
|
|
||||||
maxBytes int64
|
|
||||||
curBytes int64
|
|
||||||
items map[string]*blobDiskCacheEntry
|
|
||||||
head *blobDiskCacheEntry // most recent
|
|
||||||
tail *blobDiskCacheEntry // least recent
|
|
||||||
}
|
|
||||||
|
|
||||||
// newBlobDiskCache creates a new disk-based blob cache with the given max size.
|
|
||||||
func newBlobDiskCache(maxBytes int64) (*blobDiskCache, error) {
|
|
||||||
dir, err := os.MkdirTemp("", "vaultik-blobcache-*")
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("creating blob cache dir: %w", err)
|
|
||||||
}
|
|
||||||
return &blobDiskCache{
|
|
||||||
dir: dir,
|
|
||||||
maxBytes: maxBytes,
|
|
||||||
items: make(map[string]*blobDiskCacheEntry),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *blobDiskCache) path(key string) string {
|
|
||||||
return filepath.Join(c.dir, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *blobDiskCache) unlink(e *blobDiskCacheEntry) {
|
|
||||||
if e.prev != nil {
|
|
||||||
e.prev.next = e.next
|
|
||||||
} else {
|
|
||||||
c.head = e.next
|
|
||||||
}
|
|
||||||
if e.next != nil {
|
|
||||||
e.next.prev = e.prev
|
|
||||||
} else {
|
|
||||||
c.tail = e.prev
|
|
||||||
}
|
|
||||||
e.prev = nil
|
|
||||||
e.next = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *blobDiskCache) pushFront(e *blobDiskCacheEntry) {
|
|
||||||
e.prev = nil
|
|
||||||
e.next = c.head
|
|
||||||
if c.head != nil {
|
|
||||||
c.head.prev = e
|
|
||||||
}
|
|
||||||
c.head = e
|
|
||||||
if c.tail == nil {
|
|
||||||
c.tail = e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *blobDiskCache) evictLRU() {
|
|
||||||
if c.tail == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
victim := c.tail
|
|
||||||
c.unlink(victim)
|
|
||||||
delete(c.items, victim.key)
|
|
||||||
c.curBytes -= victim.size
|
|
||||||
_ = os.Remove(c.path(victim.key))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put writes blob data to disk cache. Entries larger than maxBytes are silently skipped.
|
|
||||||
func (c *blobDiskCache) Put(key string, data []byte) error {
|
|
||||||
entrySize := int64(len(data))
|
|
||||||
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
if entrySize > c.maxBytes {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove old entry if updating
|
|
||||||
if e, ok := c.items[key]; ok {
|
|
||||||
c.unlink(e)
|
|
||||||
c.curBytes -= e.size
|
|
||||||
_ = os.Remove(c.path(key))
|
|
||||||
delete(c.items, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := os.WriteFile(c.path(key), data, 0600); err != nil {
|
|
||||||
return fmt.Errorf("writing blob to cache: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e := &blobDiskCacheEntry{key: key, size: entrySize}
|
|
||||||
c.pushFront(e)
|
|
||||||
c.items[key] = e
|
|
||||||
c.curBytes += entrySize
|
|
||||||
|
|
||||||
for c.curBytes > c.maxBytes && c.tail != nil {
|
|
||||||
c.evictLRU()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get reads a cached blob from disk. Returns data and true on hit.
|
|
||||||
func (c *blobDiskCache) Get(key string) ([]byte, bool) {
|
|
||||||
c.mu.Lock()
|
|
||||||
e, ok := c.items[key]
|
|
||||||
if !ok {
|
|
||||||
c.mu.Unlock()
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
c.unlink(e)
|
|
||||||
c.pushFront(e)
|
|
||||||
c.mu.Unlock()
|
|
||||||
|
|
||||||
data, err := os.ReadFile(c.path(key))
|
|
||||||
if err != nil {
|
|
||||||
c.mu.Lock()
|
|
||||||
if e2, ok2 := c.items[key]; ok2 && e2 == e {
|
|
||||||
c.unlink(e)
|
|
||||||
delete(c.items, key)
|
|
||||||
c.curBytes -= e.size
|
|
||||||
}
|
|
||||||
c.mu.Unlock()
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return data, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReadAt reads a slice of a cached blob without loading the entire blob into memory.
|
|
||||||
func (c *blobDiskCache) ReadAt(key string, offset, length int64) ([]byte, error) {
|
|
||||||
c.mu.Lock()
|
|
||||||
e, ok := c.items[key]
|
|
||||||
if !ok {
|
|
||||||
c.mu.Unlock()
|
|
||||||
return nil, fmt.Errorf("key %q not in cache", key)
|
|
||||||
}
|
|
||||||
if offset+length > e.size {
|
|
||||||
c.mu.Unlock()
|
|
||||||
return nil, fmt.Errorf("read beyond blob size: offset=%d length=%d size=%d", offset, length, e.size)
|
|
||||||
}
|
|
||||||
c.unlink(e)
|
|
||||||
c.pushFront(e)
|
|
||||||
c.mu.Unlock()
|
|
||||||
|
|
||||||
f, err := os.Open(c.path(key))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer func() { _ = f.Close() }()
|
|
||||||
|
|
||||||
buf := make([]byte, length)
|
|
||||||
if _, err := f.ReadAt(buf, offset); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return buf, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Has returns whether a key exists in the cache.
|
|
||||||
func (c *blobDiskCache) Has(key string) bool {
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
_, ok := c.items[key]
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
// Size returns current total cached bytes.
|
|
||||||
func (c *blobDiskCache) Size() int64 {
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
return c.curBytes
|
|
||||||
}
|
|
||||||
|
|
||||||
// Len returns number of cached entries.
|
|
||||||
func (c *blobDiskCache) Len() int {
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
return len(c.items)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close removes the cache directory and all cached blobs.
|
|
||||||
func (c *blobDiskCache) Close() error {
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
c.items = nil
|
|
||||||
c.head = nil
|
|
||||||
c.tail = nil
|
|
||||||
c.curBytes = 0
|
|
||||||
return os.RemoveAll(c.dir)
|
|
||||||
}
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
package vaultik
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/rand"
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestBlobDiskCache_BasicGetPut(t *testing.T) {
|
|
||||||
cache, err := newBlobDiskCache(1 << 20)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer func() { _ = cache.Close() }()
|
|
||||||
|
|
||||||
data := []byte("hello world")
|
|
||||||
if err := cache.Put("key1", data); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, ok := cache.Get("key1")
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("expected cache hit")
|
|
||||||
}
|
|
||||||
if !bytes.Equal(got, data) {
|
|
||||||
t.Fatalf("got %q, want %q", got, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, ok = cache.Get("nonexistent")
|
|
||||||
if ok {
|
|
||||||
t.Fatal("expected cache miss")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBlobDiskCache_EvictionUnderPressure(t *testing.T) {
|
|
||||||
maxBytes := int64(1000)
|
|
||||||
cache, err := newBlobDiskCache(maxBytes)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer func() { _ = cache.Close() }()
|
|
||||||
|
|
||||||
for i := 0; i < 5; i++ {
|
|
||||||
data := make([]byte, 300)
|
|
||||||
if err := cache.Put(fmt.Sprintf("key%d", i), data); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if cache.Size() > maxBytes {
|
|
||||||
t.Fatalf("cache size %d exceeds max %d", cache.Size(), maxBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !cache.Has("key4") {
|
|
||||||
t.Fatal("expected key4 to be cached")
|
|
||||||
}
|
|
||||||
if cache.Has("key0") {
|
|
||||||
t.Fatal("expected key0 to be evicted")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBlobDiskCache_OversizedEntryRejected(t *testing.T) {
|
|
||||||
cache, err := newBlobDiskCache(100)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer func() { _ = cache.Close() }()
|
|
||||||
|
|
||||||
data := make([]byte, 200)
|
|
||||||
if err := cache.Put("big", data); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if cache.Has("big") {
|
|
||||||
t.Fatal("oversized entry should not be cached")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBlobDiskCache_UpdateInPlace(t *testing.T) {
|
|
||||||
cache, err := newBlobDiskCache(1 << 20)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer func() { _ = cache.Close() }()
|
|
||||||
|
|
||||||
if err := cache.Put("key1", []byte("v1")); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := cache.Put("key1", []byte("version2")); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, ok := cache.Get("key1")
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("expected hit")
|
|
||||||
}
|
|
||||||
if string(got) != "version2" {
|
|
||||||
t.Fatalf("got %q, want %q", got, "version2")
|
|
||||||
}
|
|
||||||
if cache.Len() != 1 {
|
|
||||||
t.Fatalf("expected 1 entry, got %d", cache.Len())
|
|
||||||
}
|
|
||||||
if cache.Size() != int64(len("version2")) {
|
|
||||||
t.Fatalf("expected size %d, got %d", len("version2"), cache.Size())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBlobDiskCache_ReadAt(t *testing.T) {
|
|
||||||
cache, err := newBlobDiskCache(1 << 20)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer func() { _ = cache.Close() }()
|
|
||||||
|
|
||||||
data := make([]byte, 1024)
|
|
||||||
if _, err := rand.Read(data); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := cache.Put("blob1", data); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
chunk, err := cache.ReadAt("blob1", 100, 200)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if !bytes.Equal(chunk, data[100:300]) {
|
|
||||||
t.Fatal("ReadAt returned wrong data")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = cache.ReadAt("blob1", 900, 200)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("expected error for out-of-bounds read")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = cache.ReadAt("missing", 0, 10)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("expected error for missing key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBlobDiskCache_Close(t *testing.T) {
|
|
||||||
cache, err := newBlobDiskCache(1 << 20)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := cache.Put("key1", []byte("data")); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := cache.Close(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBlobDiskCache_LRUOrder(t *testing.T) {
|
|
||||||
cache, err := newBlobDiskCache(200)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer func() { _ = cache.Close() }()
|
|
||||||
|
|
||||||
d := make([]byte, 100)
|
|
||||||
if err := cache.Put("a", d); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := cache.Put("b", d); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Access "a" to make it most recently used
|
|
||||||
cache.Get("a")
|
|
||||||
|
|
||||||
// Adding "c" should evict "b" (LRU), not "a"
|
|
||||||
if err := cache.Put("c", d); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !cache.Has("a") {
|
|
||||||
t.Fatal("expected 'a' to survive")
|
|
||||||
}
|
|
||||||
if !cache.Has("c") {
|
|
||||||
t.Fatal("expected 'c' to be present")
|
|
||||||
}
|
|
||||||
if cache.Has("b") {
|
|
||||||
t.Fatal("expected 'b' to be evicted")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -109,11 +109,7 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error {
|
|||||||
|
|
||||||
// Step 5: Restore files
|
// Step 5: Restore files
|
||||||
result := &RestoreResult{}
|
result := &RestoreResult{}
|
||||||
blobCache, err := newBlobDiskCache(4 * v.Config.BlobSizeLimit.Int64())
|
blobCache := make(map[string][]byte) // Cache downloaded and decrypted blobs
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("creating blob cache: %w", err)
|
|
||||||
}
|
|
||||||
defer func() { _ = blobCache.Close() }()
|
|
||||||
|
|
||||||
for i, file := range files {
|
for i, file := range files {
|
||||||
if v.ctx.Err() != nil {
|
if v.ctx.Err() != nil {
|
||||||
@@ -303,7 +299,7 @@ func (v *Vaultik) restoreFile(
|
|||||||
targetDir string,
|
targetDir string,
|
||||||
identity age.Identity,
|
identity age.Identity,
|
||||||
chunkToBlobMap map[string]*database.BlobChunk,
|
chunkToBlobMap map[string]*database.BlobChunk,
|
||||||
blobCache *blobDiskCache,
|
blobCache map[string][]byte,
|
||||||
result *RestoreResult,
|
result *RestoreResult,
|
||||||
) error {
|
) error {
|
||||||
// Calculate target path - use full original path under target directory
|
// Calculate target path - use full original path under target directory
|
||||||
@@ -387,7 +383,7 @@ func (v *Vaultik) restoreRegularFile(
|
|||||||
targetPath string,
|
targetPath string,
|
||||||
identity age.Identity,
|
identity age.Identity,
|
||||||
chunkToBlobMap map[string]*database.BlobChunk,
|
chunkToBlobMap map[string]*database.BlobChunk,
|
||||||
blobCache *blobDiskCache,
|
blobCache map[string][]byte,
|
||||||
result *RestoreResult,
|
result *RestoreResult,
|
||||||
) error {
|
) error {
|
||||||
// Get file chunks in order
|
// Get file chunks in order
|
||||||
@@ -421,15 +417,13 @@ func (v *Vaultik) restoreRegularFile(
|
|||||||
|
|
||||||
// Download and decrypt blob if not cached
|
// Download and decrypt blob if not cached
|
||||||
blobHashStr := blob.Hash.String()
|
blobHashStr := blob.Hash.String()
|
||||||
blobData, ok := blobCache.Get(blobHashStr)
|
blobData, ok := blobCache[blobHashStr]
|
||||||
if !ok {
|
if !ok {
|
||||||
blobData, err = v.downloadBlob(ctx, blobHashStr, blob.CompressedSize, identity)
|
blobData, err = v.downloadBlob(ctx, blobHashStr, blob.CompressedSize, identity)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("downloading blob %s: %w", blobHashStr[:16], err)
|
return fmt.Errorf("downloading blob %s: %w", blobHashStr[:16], err)
|
||||||
}
|
}
|
||||||
if putErr := blobCache.Put(blobHashStr, blobData); putErr != nil {
|
blobCache[blobHashStr] = blobData
|
||||||
log.Debug("Failed to cache blob on disk", "hash", blobHashStr[:16], "error", putErr)
|
|
||||||
}
|
|
||||||
result.BlobsDownloaded++
|
result.BlobsDownloaded++
|
||||||
result.BytesDownloaded += blob.CompressedSize
|
result.BytesDownloaded += blob.CompressedSize
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1126,23 +1126,8 @@ func (v *Vaultik) PruneDatabase() (*PruneResult, error) {
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// allowedTableNames is the exhaustive whitelist of table names that may be
|
// getTableCount returns the count of rows in a table
|
||||||
// passed to getTableCount. Any name not in this set is rejected, preventing
|
|
||||||
// SQL injection even if caller-controlled input is accidentally supplied.
|
|
||||||
var allowedTableNames = map[string]struct{}{
|
|
||||||
"files": {},
|
|
||||||
"chunks": {},
|
|
||||||
"blobs": {},
|
|
||||||
}
|
|
||||||
|
|
||||||
// getTableCount returns the number of rows in the given table.
|
|
||||||
// tableName must appear in the allowedTableNames whitelist; all other values
|
|
||||||
// are rejected with an error, preventing SQL injection.
|
|
||||||
func (v *Vaultik) getTableCount(tableName string) (int64, error) {
|
func (v *Vaultik) getTableCount(tableName string) (int64, error) {
|
||||||
if _, ok := allowedTableNames[tableName]; !ok {
|
|
||||||
return 0, fmt.Errorf("table name not allowed: %q", tableName)
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.DB == nil {
|
if v.DB == nil {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
package vaultik
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestAllowedTableNames(t *testing.T) {
|
|
||||||
// Verify the whitelist contains exactly the expected tables
|
|
||||||
expected := []string{"files", "chunks", "blobs"}
|
|
||||||
assert.Len(t, allowedTableNames, len(expected))
|
|
||||||
for _, name := range expected {
|
|
||||||
_, ok := allowedTableNames[name]
|
|
||||||
assert.True(t, ok, "expected %q in allowedTableNames", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetTableCount_RejectsInvalidNames(t *testing.T) {
|
|
||||||
v := &Vaultik{} // DB is nil, but rejection happens before DB access
|
|
||||||
v.DB = nil // explicit
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
tableName string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"allowed files", "files", false},
|
|
||||||
{"allowed chunks", "chunks", false},
|
|
||||||
{"allowed blobs", "blobs", false},
|
|
||||||
{"sql injection attempt", "files; DROP TABLE files--", true},
|
|
||||||
{"unknown table", "users", true},
|
|
||||||
{"empty string", "", true},
|
|
||||||
{"uppercase", "FILES", true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
count, err := v.getTableCount(tt.tableName)
|
|
||||||
if tt.wantErr {
|
|
||||||
assert.Error(t, err)
|
|
||||||
assert.Contains(t, err.Error(), "not allowed")
|
|
||||||
assert.Equal(t, int64(0), count)
|
|
||||||
} else {
|
|
||||||
// DB is nil so returns 0, nil for allowed names
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, int64(0), count)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -129,7 +129,7 @@ func (v *Vaultik) GetFilesystem() afero.Fs {
|
|||||||
return v.Fs
|
return v.Fs
|
||||||
}
|
}
|
||||||
|
|
||||||
// printfStdout writes formatted output to stdout.
|
// printfStdout writes formatted output to stdout for user-facing messages.
|
||||||
func (v *Vaultik) printfStdout(format string, args ...any) {
|
func (v *Vaultik) printfStdout(format string, args ...any) {
|
||||||
_, _ = fmt.Fprintf(v.Stdout, format, args...)
|
_, _ = fmt.Fprintf(v.Stdout, format, args...)
|
||||||
}
|
}
|
||||||
@@ -148,7 +148,6 @@ func (v *Vaultik) printfStderr(format string, args ...any) {
|
|||||||
func (v *Vaultik) scanStdin(a ...any) (int, error) {
|
func (v *Vaultik) scanStdin(a ...any) (int, error) {
|
||||||
return fmt.Fscanln(v.Stdin, a...)
|
return fmt.Fscanln(v.Stdin, a...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestVaultik wraps a Vaultik with captured stdout/stderr for testing
|
// TestVaultik wraps a Vaultik with captured stdout/stderr for testing
|
||||||
type TestVaultik struct {
|
type TestVaultik struct {
|
||||||
*Vaultik
|
*Vaultik
|
||||||
|
|||||||
Reference in New Issue
Block a user