Harden Harness runtime, persistence and execution for Hand
This commit is contained in:
1 parent
09c30fe2d5
commit
0972eed3ea
164 files changed
+15912
-506
No files matched your search
@@ -0,0 +1,26 @@
|
||||
# Session attachment storage
|
||||
|
||||
`Open(directory, quotaBytes)` opens a private (0700) content store. Its parent directory must already exist;
|
||||
the store directory and its parent publication are synced before use. Use
|
||||
`DefaultStoreBytes` for a 1 GiB quota. `Put(ctx, data)` publishes a synced 0600
|
||||
blob and returns a `Ref` containing its lowercase SHA-256 digest and exact byte
|
||||
length. `Read(ctx, ref)` verifies regular-file identity, size and digest. Blobs
|
||||
are limited to 32 MiB; MIME type belongs in the referring session record.
|
||||
|
||||
Publication uses a synced temporary file, exclusive hard link and directory
|
||||
sync. A cross-process lock serialises deduplication, quota admission and
|
||||
publication on Linux/macOS. Interrupted pending files are removed under that
|
||||
lock on a later new-content put. Existing published attachments are never
|
||||
evicted. A full store fails admission. Directory scanning is bounded to 8192
|
||||
entries, including control files; oversized stores require explicit maintenance.
|
||||
|
||||
References contain no caller-chosen filesystem path. File operations use
|
||||
`os.Root`; external symlinks cannot escape that root. The caller owns the
|
||||
configured private root and must not replace it with an untrusted directory.
|
||||
Do not close the store until its operations have joined. Cancellation interrupts
|
||||
lock waits and chunked I/O; the caller still owns its input byte slice until Put
|
||||
returns. Other platforms reject writer locking explicitly.
|
||||
|
||||
This package is the storage foundation. Session image references, runtime
|
||||
hydration, legacy inline-image conversion, fork copying and portable export
|
||||
packaging must be integrated before claiming attachment workflow completion.
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !darwin && !linux
|
||||
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func lock(context.Context, *os.File) error {
|
||||
return errors.New("attachment writer locking unsupported on this platform")
|
||||
}
|
||||
func unlock(*os.File) {}
|
||||
@@ -0,0 +1,34 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"golang.org/x/sys/unix"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func lock(ctx context.Context, f *os.File) error {
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, unix.EWOULDBLOCK) && !errors.Is(err, unix.EAGAIN) {
|
||||
return err
|
||||
}
|
||||
timer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func unlock(f *os.File) { _ = unix.Flock(int(f.Fd()), unix.LOCK_UN) }
|
||||
@@ -0,0 +1,267 @@
|
||||
// Package attachment stores immutable session attachments by their content hash.
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const MaxBlobBytes int64 = 32 << 20
|
||||
const DefaultStoreBytes int64 = 1 << 30
|
||||
const maxEntries = 8192
|
||||
|
||||
// Ref has no path chosen by a caller. MIME type belongs to the referring entry.
|
||||
type Ref struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
func (r Ref) Validate() error {
|
||||
if len(r.SHA256) != 64 || r.Size < 0 || r.Size > MaxBlobBytes {
|
||||
return errors.New("invalid attachment reference")
|
||||
}
|
||||
for _, c := range r.SHA256 {
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return errors.New("invalid attachment digest")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
root *os.Root
|
||||
limit int64
|
||||
}
|
||||
|
||||
// Open opens a private directory. Close after all operations join. A full store
|
||||
// rejects new content; existing session attachments are never evicted.
|
||||
func Open(dir string, limit int64) (*Store, error) {
|
||||
if limit <= 0 {
|
||||
return nil, errors.New("attachment quota must be positive")
|
||||
}
|
||||
if err := os.Mkdir(dir, 0700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Lstat(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
|
||||
return nil, errors.New("attachment directory must be private (0700)")
|
||||
}
|
||||
root, err := os.OpenRoot(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A durable blob directory also needs its name synced in the parent before
|
||||
// any session record can refer to a blob inside it. The parent must exist.
|
||||
parent, err := os.Open(filepath.Dir(dir))
|
||||
if err != nil {
|
||||
root.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = errors.Join(parent.Sync(), parent.Close()); err != nil {
|
||||
root.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{root: root, limit: limit}, nil
|
||||
}
|
||||
func (s *Store) Close() error { return s.root.Close() }
|
||||
|
||||
func (s *Store) Put(ctx context.Context, data []byte) (Ref, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if int64(len(data)) > MaxBlobBytes {
|
||||
return Ref{}, errors.New("attachment exceeds blob limit")
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
ref := Ref{SHA256: hex.EncodeToString(digest[:]), Size: int64(len(data))}
|
||||
guard, err := s.root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
defer guard.Close()
|
||||
if err := lock(ctx, guard); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
defer unlock(guard)
|
||||
if _, err := s.root.Lstat(ref.SHA256); err == nil {
|
||||
if _, err := s.Read(ctx, ref); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
// Reestablish a durability fence when reusing a prior publication.
|
||||
f, err := s.root.Open(ref.SHA256)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
err = f.Sync()
|
||||
closeErr := f.Close()
|
||||
if err = errors.Join(err, closeErr, s.sync()); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
return ref, nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return Ref{}, err
|
||||
}
|
||||
used, err := s.usage(ctx)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if ref.Size > s.limit-used {
|
||||
return Ref{}, errors.New("attachment store quota exceeded")
|
||||
}
|
||||
name := ".pending-" + rand.Text()
|
||||
f, err := s.root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
defer s.root.Remove(name)
|
||||
for offset := 0; offset < len(data); {
|
||||
if err = ctx.Err(); err != nil {
|
||||
f.Close()
|
||||
return Ref{}, err
|
||||
}
|
||||
end := min(offset+64*1024, len(data))
|
||||
n, writeErr := f.Write(data[offset:end])
|
||||
offset += n
|
||||
if writeErr != nil {
|
||||
f.Close()
|
||||
return Ref{}, writeErr
|
||||
}
|
||||
if n == 0 {
|
||||
f.Close()
|
||||
return Ref{}, io.ErrShortWrite
|
||||
}
|
||||
}
|
||||
err = f.Sync()
|
||||
err = errors.Join(err, f.Close())
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if err = s.root.Link(name, ref.SHA256); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if err = s.sync(); err != nil {
|
||||
return Ref{}, fmt.Errorf("attachment published but directory sync failed: %w", err)
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
func (s *Store) Read(ctx context.Context, ref Ref) ([]byte, error) {
|
||||
if err := ref.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := s.root.Lstat(ref.SHA256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() != ref.Size {
|
||||
return nil, errors.New("attachment is not a regular file of the declared size")
|
||||
}
|
||||
f, err := s.root.Open(ref.SHA256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
actual, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !actual.Mode().IsRegular() || !os.SameFile(info, actual) || actual.Size() != ref.Size {
|
||||
return nil, errors.New("attachment changed while opening")
|
||||
}
|
||||
data := make([]byte, 0, int(ref.Size))
|
||||
buffer := make([]byte, 64*1024)
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := f.Read(buffer)
|
||||
if int64(len(data)+n) > ref.Size {
|
||||
return nil, errors.New("attachment grew past declared size")
|
||||
}
|
||||
data = append(data, buffer[:n]...)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
if int64(len(data)) != ref.Size || hex.EncodeToString(digest[:]) != ref.SHA256 {
|
||||
return nil, errors.New("attachment integrity check failed")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (s *Store) sync() error {
|
||||
dir, err := s.root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.Join(dir.Sync(), dir.Close())
|
||||
}
|
||||
|
||||
// Called under the cross-process writer lock. Pending files are leftovers of
|
||||
// interrupted puts; published blobs are never removed by this cleanup.
|
||||
func (s *Store) usage(ctx context.Context) (int64, error) {
|
||||
dir, err := s.root.Open(".")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer dir.Close()
|
||||
entries, err := dir.ReadDir(maxEntries + 1)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return 0, err
|
||||
}
|
||||
if len(entries) > maxEntries {
|
||||
return 0, errors.New("attachment directory entry limit exceeded")
|
||||
}
|
||||
var used int64
|
||||
for _, entry := range entries {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
name := entry.Name()
|
||||
if name == ".lock" {
|
||||
continue
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return 0, errors.New("non-regular attachment store entry")
|
||||
}
|
||||
if strings.HasPrefix(name, ".pending-") {
|
||||
if err := s.root.Remove(name); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := (Ref{SHA256: name, Size: info.Size()}).Validate(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if info.Size() > s.limit-used {
|
||||
return 0, errors.New("attachment store exceeds quota")
|
||||
}
|
||||
used += info.Size()
|
||||
}
|
||||
return used, nil
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func openTest(t *testing.T, dir string, quota int64) *Store {
|
||||
t.Helper()
|
||||
if err := os.Chmod(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := Open(dir, quota)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestLargeAttachmentRoundTripAndDeduplication(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, DefaultStoreBytes)
|
||||
data := bytes.Repeat([]byte{0x42}, 12<<20)
|
||||
ref, err := s.Put(context.Background(), data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
duplicate, err := s.Put(context.Background(), data)
|
||||
if err != nil || duplicate != ref {
|
||||
t.Fatal(duplicate, err)
|
||||
}
|
||||
other := openTest(t, dir, DefaultStoreBytes)
|
||||
got, err := other.Read(context.Background(), ref)
|
||||
if err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatal("reopened blob changed", err)
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatal("deduplication left extra files", entries)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(dir, ref.SHA256))
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal(info, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentIntegrityAndTraversal(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, 100)
|
||||
ref, err := s.Put(context.Background(), []byte("original"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, ref.SHA256), []byte("modified"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Read(context.Background(), ref); err == nil {
|
||||
t.Fatal("tampering accepted")
|
||||
}
|
||||
if _, err := s.Put(context.Background(), []byte("original")); err == nil {
|
||||
t.Fatal("corrupt existing blob reused")
|
||||
}
|
||||
if _, err := s.Read(context.Background(), Ref{SHA256: "../outside", Size: 1}); err == nil {
|
||||
t.Fatal("path accepted as digest")
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, ref.SHA256)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(t.TempDir(), "secret")
|
||||
if err := os.WriteFile(outside, []byte("original"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(dir, ref.SHA256)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Read(context.Background(), ref); err == nil {
|
||||
t.Fatal("symlink accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentQuotaSerialisesIndependentStores(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
stores := []*Store{openTest(t, dir, 10), openTest(t, dir, 10)}
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
refs := make([]Ref, 2)
|
||||
for i := range stores {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
refs[i], errs[i] = stores[i].Put(context.Background(), bytes.Repeat([]byte{byte(i)}, 8))
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
success := 0
|
||||
for i, err := range errs {
|
||||
if err == nil {
|
||||
success++
|
||||
if _, err := stores[i].Read(context.Background(), refs[i]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if success != 1 {
|
||||
t.Fatalf("quota accepted %d independent writes: %v", success, errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentCancellationAndPendingCleanup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, 100)
|
||||
guard, err := s.root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer guard.Close()
|
||||
if err := lock(context.Background(), guard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err = s.Put(ctx, []byte("cancelled"))
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unlock(guard)
|
||||
if err := os.WriteFile(filepath.Join(dir, ".pending-orphan"), []byte("unfinished"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, err := s.Put(context.Background(), []byte("complete"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".pending-orphan")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("orphan retained", err)
|
||||
}
|
||||
cancelled, stop := context.WithCancel(context.Background())
|
||||
stop()
|
||||
if _, err := s.Read(cancelled, ref); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Read(context.Background(), ref); err != nil {
|
||||
t.Fatal("cancellation damaged content", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentLimitsAndPrivateDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, 100)
|
||||
if _, err := s.Put(context.Background(), make([]byte, MaxBlobBytes+1)); err == nil {
|
||||
t.Fatal("oversized blob accepted")
|
||||
}
|
||||
if _, err := s.Put(context.Background(), make([]byte, 101)); err == nil {
|
||||
t.Fatal("quota exceeded")
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name() != ".lock" {
|
||||
t.Fatal("failed put published file", entry.Name())
|
||||
}
|
||||
}
|
||||
if _, err := Open(t.TempDir(), 0); err == nil {
|
||||
t.Fatal("invalid quota accepted")
|
||||
}
|
||||
public := t.TempDir()
|
||||
if err := os.Chmod(public, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Open(public, 100); err == nil {
|
||||
t.Fatal("public directory accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user