Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+32
View File
@@ -0,0 +1,32 @@
package attachment
import (
"time"
"github.com/google/uuid"
)
type FileStatus string
const (
FilePending FileStatus = "pending"
FileReady FileStatus = "ready"
FileFailed FileStatus = "failed"
)
type Attachment struct {
ID, ChatID, OwnerID uuid.UUID
Filename string
FileHash []byte
SizeBytes int64
MIMEType string
Status FileStatus
CreatedAt time.Time
}
type UploadInput struct {
ChatID uuid.UUID
Filename string
MIMEType string
SizeBytes int64
}
+25
View File
@@ -0,0 +1,25 @@
package attachment
import (
"context"
"errors"
"io"
"time"
)
var ErrObjectMissing = errors.New("object missing")
type Object struct {
Key string
Size int64
Modified time.Time
}
type Blobs interface {
Put(ctx context.Context, key string, body io.Reader, size int64, mimeType string) error
Open(ctx context.Context, key string) (io.ReadCloser, error)
Stat(ctx context.Context, key string) (Object, error)
Copy(ctx context.Context, sourceKey, destinationKey string) error
Delete(ctx context.Context, key string) error
List(ctx context.Context, prefix, after string, limit int) ([]Object, error)
}
+143
View File
@@ -0,0 +1,143 @@
package attachment
import (
"encoding/hex"
"io"
"log/slog"
"mime"
"net/http"
"strconv"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Handler struct{ s *Service }
func NewHandler(s *Service) *Handler { return &Handler{s} }
func (h *Handler) Register(protected, binaryProtected gin.IRouter) {
binaryProtected.POST("/chats/:chat_id/attachments", httpx.WithUser(h.upload))
protected.GET("/attachments/:attachment_id", httpx.WithUser(h.metadata))
binaryProtected.GET("/attachments/:attachment_id/content", httpx.WithUser(h.content))
}
type Response struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
// Lab4's shared response contract requires variants=[], even without processing.
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func toResponse(a Attachment) Response {
return Response{
ID: a.ID.String(),
ChatID: a.ChatID.String(),
OwnerID: a.OwnerID.String(),
Filename: a.Filename,
ContentType: a.MIMEType,
SizeBytes: a.SizeBytes,
SHA256: hex.EncodeToString(a.FileHash),
Status: string(a.Status),
Variants: []any{},
CreatedAt: httpx.Timestamp(a.CreatedAt),
UpdatedAt: httpx.Timestamp(a.CreatedAt),
}
}
func (h *Handler) upload(c *gin.Context, actor uuid.UUID) {
id, err := ident.Parse(c.Param("chat_id"))
if err != nil {
httpx.Error(c, apperr.Invalid("chat_id must be a UUID"))
return
}
names := c.Request.URL.Query()["filename"]
if len(names) != 1 {
httpx.Error(c, apperr.Invalid("one filename is required"))
return
}
if err := ValidateFilename(names[0]); err != nil {
httpx.Error(c, err)
return
}
media, params, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || len(params) > 0 {
httpx.Error(c, apperr.UnsupportedMedia("Content-Type must be image/png or image/jpeg"))
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.s.config.MaxBytes)
input := UploadInput{
ChatID: id,
Filename: names[0],
MIMEType: media,
SizeBytes: c.Request.ContentLength,
}
a, err := h.s.Upload(c.Request.Context(), actor, input, c.Request.Body)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusCreated, toResponse(a))
}
func attachmentID(c *gin.Context) (uuid.UUID, error) {
id, err := ident.Parse(c.Param("attachment_id"))
if err != nil {
return uuid.Nil, apperr.Invalid("attachment_id must be a UUID")
}
return id, nil
}
func (h *Handler) metadata(c *gin.Context, actor uuid.UUID) {
id, err := attachmentID(c)
if err != nil {
httpx.Error(c, err)
return
}
a, err := h.s.Get(c.Request.Context(), actor, id)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, toResponse(a))
}
func (h *Handler) content(c *gin.Context, actor uuid.UUID) {
id, err := attachmentID(c)
if err != nil {
httpx.Error(c, err)
return
}
variant, present := c.GetQuery("variant")
if present && variant != "original" {
httpx.Error(c, apperr.Invalid("variant must be original"))
return
}
a, r, err := h.s.Content(c.Request.Context(), actor, id)
if err != nil {
httpx.Error(c, err)
return
}
defer func() {
if err := r.Close(); err != nil {
slog.Warn("download reader close failed", "request_id", httpx.RequestID(c), "error", err)
}
}()
c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Content-Type", a.MIMEType)
c.Header("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
c.Status(http.StatusOK)
if _, err := io.CopyN(c.Writer, r, a.SizeBytes); err != nil {
slog.Error("download interrupted", "request_id", httpx.RequestID(c), "error", err)
}
}
+23
View File
@@ -0,0 +1,23 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"github.com/jackc/pgx/v5"
)
// LockHash serializes CAS publication and collection until the transaction ends.
// A collision in the signed first eight digest bytes only adds serialization.
func LockHash(ctx context.Context, tx pgx.Tx, hash []byte) error {
if len(hash) != sha256.Size {
return errors.New("attachment: lock requires a SHA256 hash")
}
_, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, int64(binary.BigEndian.Uint64(hash[:8])))
return err
}
func BlobKey(hash []byte) string { return "blobs/" + hex.EncodeToString(hash) }
+504
View File
@@ -0,0 +1,504 @@
package attachment
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const (
reconcilePageSize = 500
reconcileOperationTimeout = 30 * time.Second
)
type Finding struct {
Kind string `json:"kind"`
Key string `json:"key"`
Action string `json:"action"`
Applied bool `json:"applied"`
}
// SQLQueries counts SQL statements, including transaction control and locks.
// S3Calls counts calls to the Blobs port, including each list page and deep GET.
type Stats struct {
ElapsedMS int64 `json:"elapsed_ms"`
SQLQueries int64 `json:"sql_queries"`
S3Calls int64 `json:"s3_calls"`
ScannedFiles int64 `json:"scanned_files"`
ScannedObjects int64 `json:"scanned_objects"`
Findings int64 `json:"findings"`
Repaired int64 `json:"repaired"`
}
type Reconciler struct {
db *pgxpool.Pool
blobs Blobs
grace time.Duration
}
type ReconcileOptions struct {
Apply bool
Deep bool
}
func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconciler, error) {
if db == nil || blobs == nil {
return nil, errors.New("reconcile: database and blobs are required")
}
if grace == 0 {
grace = time.Hour
}
if grace < 2*time.Minute {
return nil, errors.New("reconcile: grace must be at least two minutes")
}
return &Reconciler{db: db, blobs: blobs, grace: grace}, nil
}
// Run streams findings and keeps at most one page of metadata in memory.
// Dry runs only read storage. Each apply candidate is checked again under the
// publisher's transaction lock; no scan snapshot authorizes a later mutation.
func (r *Reconciler) Run(ctx context.Context, options ReconcileOptions, emit func(Finding)) (stats Stats, err error) {
started := time.Now()
defer func() { stats.ElapsedMS = time.Since(started).Milliseconds() }()
run := reconcileRun{
r: r,
ctx: ctx,
apply: options.Apply,
deep: options.Deep,
emit: emit,
stats: &stats,
cutoff: started.Add(-r.grace),
}
for _, prefix := range []string{"staging/", "blobs/"} {
if err = run.objects(prefix); err != nil {
return stats, err
}
}
err = run.files()
return stats, err
}
type reconcileRun struct {
r *Reconciler
ctx context.Context
apply, deep bool
emit func(Finding)
stats *Stats
cutoff time.Time
}
func (s *reconcileRun) note(f *Finding) {
if f == nil {
return
}
s.stats.Findings++
if f.Applied {
s.stats.Repaired++
}
if s.emit != nil {
s.emit(*f)
}
}
func (s *reconcileRun) old(modified time.Time) bool {
// Unknown timestamps must never authorize collection.
return !modified.IsZero() && modified.Before(s.cutoff)
}
func (s *reconcileRun) objects(prefix string) error {
after := ""
for {
if err := s.ctx.Err(); err != nil {
return err
}
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
page, err := s.r.blobs.List(opCtx, prefix, after, reconcilePageSize)
cancel()
if err != nil {
return fmt.Errorf("reconcile list %s: %w", prefix, err)
}
if len(page) == 0 {
return nil
}
var known map[string]bool
if prefix == "blobs/" {
known, err = s.knownFiles(page)
if err != nil {
return err
}
}
for _, obj := range page {
if obj.Key <= after {
return errors.New("reconcile: object page did not advance")
}
after = obj.Key
s.stats.ScannedObjects++
if !s.old(obj.Modified) {
continue
}
var finding *Finding
if prefix == "staging/" {
finding, err = s.staging(obj)
} else {
finding, err = s.orphan(obj, known[obj.Key])
}
if err != nil {
return fmt.Errorf("reconcile %s: %w", obj.Key, err)
}
s.note(finding)
}
}
}
func (s *reconcileRun) stat(key string) (Object, error) {
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
return s.r.blobs.Stat(opCtx, key)
}
func (s *reconcileRun) delete(key string) error {
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
err := s.r.blobs.Delete(opCtx, key)
if errors.Is(err, ErrObjectMissing) {
return nil
}
return err
}
func (s *reconcileRun) staging(obj Object) (*Finding, error) {
f := &Finding{Kind: "stale_staging", Key: obj.Key, Action: "delete_object"}
if !s.apply {
return f, nil
}
current, err := s.stat(obj.Key)
if errors.Is(err, ErrObjectMissing) {
return nil, nil
}
if err != nil {
return nil, err
}
if !s.old(current.Modified) {
return nil, nil
}
if err = s.delete(obj.Key); err != nil {
return nil, err
}
f.Applied = true
return f, nil
}
func (s *reconcileRun) knownFiles(page []Object) (map[string]bool, error) {
hashes := make([][]byte, 0, len(page))
for _, obj := range page {
if !s.old(obj.Modified) {
continue
}
hash, err := hex.DecodeString(obj.Key[len("blobs/"):])
if err == nil && len(hash) == sha256.Size && BlobKey(hash) == obj.Key {
hashes = append(hashes, hash)
}
}
known := make(map[string]bool, len(hashes))
if len(hashes) == 0 {
return known, nil
}
s.stats.SQLQueries++
rows, err := s.r.db.Query(s.ctx, `
SELECT hash FROM files WHERE hash = ANY($1::bytea[])`, hashes)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var hash []byte
if err := rows.Scan(&hash); err != nil {
return nil, err
}
known[BlobKey(hash)] = true
}
return known, rows.Err()
}
func (s *reconcileRun) orphan(obj Object, known bool) (*Finding, error) {
hash, err := hex.DecodeString(obj.Key[len("blobs/"):])
if err != nil || len(hash) != sha256.Size || BlobKey(hash) != obj.Key {
return &Finding{Kind: "invalid_blob_key", Key: obj.Key, Action: "report"}, nil
}
if known {
return nil, nil
}
f := &Finding{Kind: "orphan_blob", Key: obj.Key, Action: "delete_object"}
if !s.apply {
return f, nil
}
return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
op := *s
op.ctx = opCtx
var exists bool
s.stats.SQLQueries++
if err := tx.QueryRow(opCtx, `
SELECT EXISTS (SELECT 1 FROM files WHERE hash = $1)`, hash).Scan(&exists); err != nil {
return nil, err
}
if exists {
return nil, nil
}
current, err := op.stat(obj.Key)
if errors.Is(err, ErrObjectMissing) {
return nil, nil
}
if err != nil {
return nil, err
}
if !s.old(current.Modified) {
return nil, nil
}
if err = op.delete(obj.Key); err != nil {
return nil, err
}
f.Applied = true
return f, nil
})
}
// locked also covers hashes without a files row: a publisher and an orphan
// collector therefore cannot pass each other's existence check concurrently.
func (s *reconcileRun) locked(hash []byte, fn func(context.Context, pgx.Tx) (*Finding, error)) (*Finding, error) {
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
s.stats.SQLQueries++
tx, err := s.r.db.Begin(opCtx)
if err != nil {
return nil, err
}
committed := false
defer func() {
if !committed {
cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s.stats.SQLQueries++
_ = tx.Rollback(cleanup)
}
}()
// Pool defaults cover ordinary requests; object I/O can outlive those
// idle limits. The operation deadline bounds the entire locked candidate.
s.stats.SQLQueries++
if _, err = tx.Exec(opCtx, `SET LOCAL idle_in_transaction_session_timeout='35s'`); err != nil {
return nil, err
}
s.stats.SQLQueries++
if err = LockHash(opCtx, tx, hash); err != nil {
return nil, err
}
f, err := fn(opCtx, tx)
if err != nil {
return nil, err
}
s.stats.SQLQueries++
err = tx.Commit(opCtx)
committed = true // pgx closes the transaction even when COMMIT fails.
if err != nil {
return nil, err
}
return f, nil
}
type reconcileFile struct {
hash []byte
size int64
status FileStatus
created time.Time
referenced bool
}
func (s *reconcileRun) files() error {
after := []byte{}
for {
if err := s.ctx.Err(); err != nil {
return err
}
s.stats.SQLQueries++
rows, err := s.r.db.Query(s.ctx, `
SELECT f.hash, f.size_bytes, f.status, f.created_at,
EXISTS (SELECT 1 FROM attachments a WHERE a.file_hash = f.hash)
FROM files f
WHERE f.hash > $1
ORDER BY f.hash
LIMIT $2`, after, reconcilePageSize)
if err != nil {
return err
}
page := make([]reconcileFile, 0, reconcilePageSize)
for rows.Next() {
var f reconcileFile
if err = rows.Scan(&f.hash, &f.size, &f.status, &f.created, &f.referenced); err != nil {
rows.Close()
return err
}
page = append(page, f)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
if len(page) == 0 {
return nil
}
// Close the page's SQL rows before acquiring a transaction connection.
for _, f := range page {
after = f.hash
s.stats.ScannedFiles++
if !s.candidate(f) {
continue
}
finding, err := s.inspect(f)
if err == nil && s.apply && finding != nil && finding.Action != "report" {
finding, err = s.repairFile(f.hash)
}
if err != nil {
return fmt.Errorf("reconcile file %s: %w", BlobKey(f.hash), err)
}
s.note(finding)
}
}
}
func (s *reconcileRun) repairFile(hash []byte) (*Finding, error) {
return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
op := *s
op.ctx = opCtx
var current reconcileFile
s.stats.SQLQueries++
err := tx.QueryRow(opCtx, `
SELECT f.hash, f.size_bytes, f.status, f.created_at,
EXISTS (SELECT 1 FROM attachments a WHERE a.file_hash = f.hash)
FROM files f
WHERE f.hash = $1
FOR UPDATE OF f`, hash).
Scan(&current.hash, &current.size, &current.status, &current.created, &current.referenced)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
if !op.candidate(current) {
return nil, nil
}
finding, err := op.inspect(current)
if err != nil || finding == nil {
return finding, err
}
switch finding.Action {
case "delete_file":
// Delete bytes first. A failed SQL commit leaves an unreferenced
// missing row that the next pass can safely finish collecting.
if err := op.delete(finding.Key); err != nil {
return nil, err
}
s.stats.SQLQueries++
_, err = tx.Exec(opCtx, `DELETE FROM files WHERE hash = $1`, hash)
case "mark_failed":
s.stats.SQLQueries++
_, err = tx.Exec(opCtx, `UPDATE files SET status = $2 WHERE hash = $1`, hash, FileFailed)
default:
return finding, nil
}
if err != nil {
return nil, err
}
finding.Applied = true
return finding, nil
})
}
func (s *reconcileRun) candidate(f reconcileFile) bool {
if !s.old(f.created) {
return false
}
if !f.referenced {
return f.status == FilePending || f.status == FileReady
}
return f.status == FileReady || f.status == FileFailed
}
func (s *reconcileRun) inspect(f reconcileFile) (*Finding, error) {
key := BlobKey(f.hash)
if !f.referenced {
// A publication that rolled back can leave fresh bytes behind an old
// pending row. Both the metadata and the current object must be old.
obj, err := s.stat(key)
if err != nil && !errors.Is(err, ErrObjectMissing) {
return nil, err
}
if err == nil && !s.old(obj.Modified) {
return nil, nil
}
return &Finding{Kind: "unreferenced_" + string(f.status), Key: key, Action: "delete_file"}, nil
}
obj, err := s.stat(key)
if errors.Is(err, ErrObjectMissing) {
if f.status == FileFailed {
return nil, nil
}
return &Finding{Kind: "missing_blob", Key: key, Action: "mark_failed"}, nil
}
if err != nil {
return nil, err
}
if obj.Size != f.size {
return &Finding{Kind: "size_mismatch", Key: key, Action: "report"}, nil
}
if s.deep {
match, err := s.verify(f)
if err != nil {
return nil, err
}
if !match {
return &Finding{Kind: "hash_mismatch", Key: key, Action: "report"}, nil
}
}
// A failed file stays failed even when the key reappears. Recovery requires
// an explicit publisher; a shallow HEAD cannot prove content integrity.
if f.status == FileFailed {
return &Finding{Kind: "failed_present", Key: key, Action: "report"}, nil
}
return nil, nil
}
func (s *reconcileRun) verify(f reconcileFile) (bool, error) {
if f.size < 0 || f.size == math.MaxInt64 {
return false, errors.New("reconcile: invalid file size")
}
s.stats.S3Calls++
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
defer cancel()
body, err := s.r.blobs.Open(opCtx, BlobKey(f.hash))
if err != nil {
return false, err
}
hash := sha256.New()
n, readErr := io.Copy(hash, io.LimitReader(body, f.size+1))
closeErr := body.Close()
if readErr != nil {
return false, readErr
}
if closeErr != nil {
return false, closeErr
}
return n == f.size && bytes.Equal(hash.Sum(nil), f.hash), nil
}
+731
View File
@@ -0,0 +1,731 @@
package attachment_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/attachment"
"messenger/internal/testenv"
)
func TestReconcileBlobKey(t *testing.T) {
hash, _ := hex.DecodeString("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
if got := attachment.BlobKey(hash); got != "blobs/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
t.Fatalf("blob key: %q", got)
}
}
// Only object storage is doubled: SQL, transactions, FKs and advisory locks are real.
type reconcileBlobs struct {
mu sync.Mutex
objects map[string]attachment.Object
bodies map[string][]byte
statErr, deleteErr, openErr error
listed func(string)
stating func(string)
opening func(string) io.ReadCloser
writes, readBytes int
limits []int
}
func newReconcileBlobs() *reconcileBlobs {
return &reconcileBlobs{objects: make(map[string]attachment.Object), bodies: make(map[string][]byte)}
}
func (b *reconcileBlobs) add(key string, body []byte, modified time.Time) {
b.mu.Lock()
defer b.mu.Unlock()
b.objects[key] = attachment.Object{Key: key, Size: int64(len(body)), Modified: modified}
b.bodies[key] = bytes.Clone(body)
}
func (b *reconcileBlobs) has(key string) bool {
b.mu.Lock()
defer b.mu.Unlock()
_, ok := b.objects[key]
return ok
}
func (b *reconcileBlobs) Put(_ context.Context, key string, r io.Reader, size int64, _ string) error {
body, err := io.ReadAll(io.LimitReader(r, size+1))
if err != nil {
return err
}
if int64(len(body)) != size {
return io.ErrUnexpectedEOF
}
b.add(key, body, time.Now())
b.mu.Lock()
b.writes++
b.mu.Unlock()
return nil
}
func (b *reconcileBlobs) Copy(_ context.Context, source, dest string) error {
b.mu.Lock()
body, ok := b.bodies[source]
b.mu.Unlock()
if !ok {
return attachment.ErrObjectMissing
}
b.add(dest, body, time.Now())
b.mu.Lock()
b.writes++
b.mu.Unlock()
return nil
}
func (b *reconcileBlobs) Open(_ context.Context, key string) (io.ReadCloser, error) {
if b.openErr != nil {
return nil, b.openErr
}
if b.opening != nil {
return b.opening(key), nil
}
b.mu.Lock()
defer b.mu.Unlock()
body, ok := b.bodies[key]
if !ok {
return nil, attachment.ErrObjectMissing
}
return io.NopCloser(bytes.NewReader(body)), nil
}
func (b *reconcileBlobs) Stat(_ context.Context, key string) (attachment.Object, error) {
if b.stating != nil {
b.stating(key)
}
b.mu.Lock()
defer b.mu.Unlock()
if b.statErr != nil {
return attachment.Object{}, b.statErr
}
obj, ok := b.objects[key]
if !ok {
return attachment.Object{}, fmt.Errorf("head: %w", attachment.ErrObjectMissing)
}
return obj, nil
}
func (b *reconcileBlobs) Delete(_ context.Context, key string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.deleteErr != nil {
return b.deleteErr
}
delete(b.objects, key)
delete(b.bodies, key)
b.writes++
return nil
}
func (b *reconcileBlobs) List(_ context.Context, prefix, after string, limit int) ([]attachment.Object, error) {
b.mu.Lock()
b.limits = append(b.limits, limit)
if limit < 1 || limit > 500 {
b.mu.Unlock()
return nil, errors.New("unbounded page")
}
var page []attachment.Object
for key, obj := range b.objects {
if strings.HasPrefix(key, prefix) && key > after {
page = append(page, obj)
}
}
sort.Slice(page, func(i, j int) bool { return page[i].Key < page[j].Key })
if len(page) > limit {
page = page[:limit]
}
b.mu.Unlock()
if b.listed != nil {
b.listed(prefix)
}
return page, nil
}
type reconcileFixture struct {
t *testing.T
db *pgxpool.Pool
b *reconcileBlobs
user, chat, message uuid.UUID
}
func reconcileSetup(t *testing.T, db *testenv.DB) *reconcileFixture {
t.Helper()
db.Reset(t)
f := &reconcileFixture{t: t, db: db.Pool, b: newReconcileBlobs(), user: uuid.New(), chat: uuid.New(), message: uuid.New()}
f.exec(`INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,'reconcile','Reconcile','unused',now())`, f.user)
f.exec(`INSERT INTO chats(id,title,created_at) VALUES($1,'reconcile',now())`, f.chat)
f.exec(`INSERT INTO messages(chat_id,id,sender_id,text,created_at) VALUES($1,$2,$3,'preserve',now())`, f.chat, f.message, f.user)
return f
}
func (f *reconcileFixture) exec(sql string, args ...any) {
f.t.Helper()
if _, err := f.db.Exec(context.Background(), sql, args...); err != nil {
f.t.Fatal(err)
}
}
func (f *reconcileFixture) file(body, status string, age time.Duration, referenced, present bool) []byte {
f.t.Helper()
hash := sha256.Sum256([]byte(body))
f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png',$3,$4)`, hash[:], len(body), status, time.Now().Add(-age))
if referenced {
id := uuid.New()
f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'image.png',$4,now())`, id, f.chat, f.user, hash[:])
f.exec(`INSERT INTO message_attachments(chat_id,message_id,attachment_id,ordinal)
VALUES($1,$2,$3,(SELECT count(*) FROM message_attachments WHERE chat_id=$1 AND message_id=$2))`, f.chat, f.message, id)
}
if present {
f.b.add(attachment.BlobKey(hash[:]), []byte(body), time.Now().Add(-age))
}
return hash[:]
}
func (f *reconcileFixture) status(hash []byte) string {
f.t.Helper()
var s string
err := f.db.QueryRow(context.Background(), `SELECT status FROM files WHERE hash=$1`, hash).Scan(&s)
if errors.Is(err, pgx.ErrNoRows) {
return ""
}
if err != nil {
f.t.Fatal(err)
}
return s
}
func (f *reconcileFixture) run(apply, deep bool) (attachment.Stats, []attachment.Finding, error) {
f.t.Helper()
r, err := attachment.NewReconciler(f.db, f.b, 0)
if err != nil {
f.t.Fatal(err)
}
var found []attachment.Finding
options := attachment.ReconcileOptions{Apply: apply, Deep: deep}
stats, err := r.Run(context.Background(), options, func(v attachment.Finding) { found = append(found, v) })
return stats, found, err
}
func TestReconciler(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
t.Run("healthy apply does not block publication", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("healthy", "ready", 2*time.Hour, true, true)
tx, err := db.Pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err := attachment.LockHash(ctx, tx, hash); err != nil {
t.Fatal(err)
}
r, err := attachment.NewReconciler(f.db, f.b, time.Hour)
if err != nil {
t.Fatal(err)
}
scanCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
stats, err := r.Run(scanCtx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil)
if err != nil || stats.Findings != 0 || stats.Repaired != 0 {
t.Fatalf("healthy inspection waited for publication: %+v %v", stats, err)
}
})
t.Run("constructor validates and defaults grace", func(t *testing.T) {
f := reconcileSetup(t, db)
for _, grace := range []time.Duration{-time.Second, time.Minute} {
if _, err := attachment.NewReconciler(f.db, f.b, grace); err == nil {
t.Fatalf("accepted grace %v", grace)
}
}
if _, err := attachment.NewReconciler(nil, f.b, 0); err == nil {
t.Fatal("accepted nil DB")
}
if _, err := attachment.NewReconciler(f.db, nil, 0); err == nil {
t.Fatal("accepted nil blobs")
}
if _, err := attachment.NewReconciler(f.db, f.b, 2*time.Minute); err != nil {
t.Fatal(err)
}
fresh := f.file("half hour", "ready", 30*time.Minute, false, true)
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || f.status(fresh) != "ready" {
t.Fatalf("default grace: %+v %v", stats, err)
}
})
t.Run("dry run then apply then repeat preserves fresh referenced and message links", func(t *testing.T) {
f := reconcileSetup(t, db)
old := 2 * time.Hour
pending := f.file("pending", "pending", old, false, true)
unused := f.file("unused", "ready", old, false, true)
used := f.file("used", "ready", old, true, true)
fresh := f.file("fresh", "pending", time.Minute, false, true)
missing := f.file("missing", "ready", old, true, false)
f.b.add("staging/old", []byte("old"), time.Now().Add(-old))
f.b.add("staging/fresh", []byte("new"), time.Now())
orphan := sha256.Sum256([]byte("orphan"))
orphanKey := attachment.BlobKey(orphan[:])
f.b.add(orphanKey, []byte("orphan"), time.Now().Add(-old))
stats, findings, err := f.run(false, false)
if err != nil || stats.Repaired != 0 || stats.Findings != 5 || len(findings) != 5 {
t.Fatalf("dry: %+v %v %+v", stats, err, findings)
}
if f.b.writes != 0 || f.status(pending) != "pending" || f.status(missing) != "ready" {
t.Fatal("dry run mutated storage")
}
for _, finding := range findings {
if finding.Applied {
t.Fatal("dry finding marked applied")
}
}
stats, findings, err = f.run(true, false)
if err != nil || stats.Repaired != 5 {
t.Fatalf("apply: %+v %v %+v", stats, err, findings)
}
if f.status(pending) != "" || f.status(unused) != "" || f.status(missing) != "failed" {
t.Fatal("metadata repair incorrect")
}
if f.b.has(orphanKey) || f.b.has("staging/old") || !f.b.has("staging/fresh") || !f.b.has(attachment.BlobKey(used)) || !f.b.has(attachment.BlobKey(fresh)) {
t.Fatal("incorrect object collection")
}
var links int
if err := f.db.QueryRow(ctx, `SELECT count(*) FROM message_attachments`).Scan(&links); err != nil || links != 2 {
t.Fatalf("message links lost: %d %v", links, err)
}
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 0 {
t.Fatalf("repeat: %+v %v", stats, err)
}
})
t.Run("outage is not missing and failed delete keeps row", func(t *testing.T) {
f := reconcileSetup(t, db)
used := f.file("used", "ready", 2*time.Hour, true, true)
outage := errors.New("injected S3 outage")
f.b.statErr = outage
stats, _, err := f.run(true, false)
if !errors.Is(err, outage) || stats.Repaired != 0 || f.status(used) != "ready" {
t.Fatalf("outage: %+v %v", stats, err)
}
f.b.statErr = nil
unused := f.file("unused", "pending", 2*time.Hour, false, true)
f.b.deleteErr = outage
_, _, err = f.run(true, false)
if !errors.Is(err, outage) || f.status(unused) != "pending" {
t.Fatalf("delete failure: %v", err)
}
})
t.Run("deep reports corruption and never revives failed without verification", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, true)
f.b.add(attachment.BlobKey(hash), []byte("evil"), time.Now().Add(-2*time.Hour))
stats, found, err := f.run(true, true)
if err != nil || stats.Findings != 1 || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "hash_mismatch" || f.status(hash) != "ready" || !f.b.has(attachment.BlobKey(hash)) {
t.Fatalf("deep: %+v %v %+v", stats, err, found)
}
f.exec(`UPDATE files SET status='failed' WHERE hash=$1`, hash)
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 0 || f.status(hash) != "failed" {
t.Fatal("shallow revived failed file")
}
stats, _, err = f.run(true, true)
if err != nil || stats.Repaired != 0 || f.status(hash) != "failed" {
t.Fatal("corrupt file revived")
}
})
t.Run("wrong size reports only and fresh missing stays ready", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("sized", "ready", 2*time.Hour, true, true)
f.b.add(attachment.BlobKey(hash), []byte("longer body"), time.Now().Add(-2*time.Hour))
fresh := f.file("new missing", "ready", time.Minute, true, false)
stats, found, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || stats.Findings != 1 || found[0].Kind != "size_mismatch" || f.status(fresh) != "ready" {
t.Fatalf("size/fresh: %+v %v %+v", stats, err, found)
}
})
t.Run("orphan rechecks current object age", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := sha256.Sum256([]byte("orphan"))
key := attachment.BlobKey(hash[:])
f.b.add(key, []byte("orphan"), time.Now().Add(-2*time.Hour))
f.b.listed = func(prefix string) {
if prefix == "blobs/" {
f.b.add(key, []byte("republished"), time.Now())
}
}
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || !f.b.has(key) {
t.Fatalf("fresh replacement deleted: %+v %v", stats, err)
}
})
t.Run("row rechecks references after taking lock", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("race refs", "ready", 2*time.Hour, false, true)
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err = attachment.LockHash(ctx, tx, hash); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
r, _ := attachment.NewReconciler(f.db, f.b, 0)
_, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
done <- err
}()
waitReconcileLock(t, ctx, f.db)
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) VALUES($1,$2,$3,'race.png',$4,now())`, uuid.New(), f.chat, f.user, hash)
if err != nil {
t.Fatal(err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
if err = <-done; err != nil {
t.Fatal(err)
}
if f.status(hash) != "ready" || !f.b.has(attachment.BlobKey(hash)) {
t.Fatal("new reference collected")
}
})
t.Run("concurrent upload lock prevents orphan collection", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := sha256.Sum256([]byte("publishing"))
key := attachment.BlobKey(hash[:])
f.b.add(key, []byte("publishing"), time.Now().Add(-2*time.Hour))
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err = attachment.LockHash(ctx, tx, hash[:]); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
r, _ := attachment.NewReconciler(f.db, f.b, 0)
_, err := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
done <- err
}()
waitReconcileLock(t, ctx, f.db)
if _, err = tx.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES($1,10,'image/png','ready')`, hash[:]); err != nil {
t.Fatal(err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
if err = <-done; err != nil {
t.Fatal(err)
}
if !f.b.has(key) || f.status(hash[:]) != "ready" {
t.Fatal("published blob collected")
}
})
t.Run("signed big endian lock key matches publisher", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := make([]byte, 32)
for i := 0; i < 8; i++ {
hash[i] = 255
}
hash[7] = 254
tx, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
if err = attachment.LockHash(ctx, tx, hash); err != nil {
t.Fatal(err)
}
other, err := f.db.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer other.Rollback(ctx)
var acquired bool
if err = other.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(-2::bigint)`).Scan(&acquired); err != nil || acquired {
t.Fatalf("lock mismatch: %v %v", acquired, err)
}
})
t.Run("keyset pages tolerate deletes and report costs", func(t *testing.T) {
f := reconcileSetup(t, db)
for i := 0; i < 1003; i++ {
f.b.add(fmt.Sprintf("staging/%04d", i), []byte("x"), time.Now().Add(-2*time.Hour))
}
f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) SELECT decode(lpad(to_hex(i),64,'0'),'hex'),1,'image/png','pending',now()-interval '2 hour' FROM generate_series(1,1003) AS i`)
stats, _, err := f.run(true, false)
if err != nil || stats.ScannedFiles != 1003 || stats.ScannedObjects != 1003 || stats.Repaired != 2006 {
t.Fatalf("pages: %+v %v", stats, err)
}
var n int
if err := f.db.QueryRow(ctx, `SELECT count(*) FROM files`).Scan(&n); err != nil || n != 0 {
t.Fatalf("skipped rows: %d %v", n, err)
}
if len(f.b.limits) < 4 || stats.SQLQueries == 0 || stats.S3Calls == 0 {
t.Fatalf("missing paging/costs: %+v", stats)
}
raw, err := json.Marshal(stats)
if err != nil {
t.Fatal(err)
}
for _, key := range []string{"elapsed_ms", "sql_queries", "s3_calls", "scanned_files", "scanned_objects", "findings", "repaired"} {
if !bytes.Contains(raw, []byte(`"`+key+`":`)) {
t.Fatalf("missing JSON key %s: %s", key, raw)
}
}
})
t.Run("old blob existence checks are batched by page", func(t *testing.T) {
f := reconcileSetup(t, db)
f.exec(`INSERT INTO files(hash,size_bytes,mime_type,status,created_at) SELECT decode(lpad(to_hex(i),64,'0'),'hex'),1,'image/png','ready',now()-interval '2 hour' FROM generate_series(1,1003) AS i`)
f.exec(`INSERT INTO attachments(id,chat_id,owner_id,filename,file_hash,created_at) SELECT gen_random_uuid(),$1,$2,'batch.png',hash,now() FROM files`, f.chat, f.user)
for i := 1; i <= 1003; i++ {
f.b.add(fmt.Sprintf("blobs/%064x", i), []byte("x"), time.Now().Add(-2*time.Hour))
}
stats, _, err := f.run(false, false)
if err != nil || stats.SQLQueries > 8 || stats.SQLQueries == 0 || stats.ScannedFiles != 1003 || stats.Findings != 0 {
t.Fatalf("per-object SQL lookup: %+v %v", stats, err)
}
})
}
func waitReconcileLock(t *testing.T, ctx context.Context, db *pgxpool.Pool) {
t.Helper()
deadline := time.NewTimer(5 * time.Second)
defer deadline.Stop()
tick := time.NewTicker(10 * time.Millisecond)
defer tick.Stop()
for {
var waiting bool
if err := db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype='advisory' AND NOT granted)`).Scan(&waiting); err != nil {
t.Fatal(err)
}
if waiting {
return
}
select {
case <-deadline.C:
t.Fatal("reconciler did not wait on publisher advisory lock")
case <-tick.C:
}
}
}
type reconcileEndless struct {
read int64
closed bool
}
func (r *reconcileEndless) Read(p []byte) (int, error) {
for i := range p {
p[i] = 'x'
}
r.read += int64(len(p))
return len(p), nil
}
func (r *reconcileEndless) Close() error { r.closed = true; return nil }
func TestReconcilerFailureBoundaries(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
t.Run("slow object call survives pool idle transaction timeout", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("slow object", "pending", 2*time.Hour, false, true)
cfg := f.db.Config()
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "100ms"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
f.db = pool
f.b.stating = func(string) { time.Sleep(250 * time.Millisecond) }
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 1 || f.status(hash) != "" {
t.Fatalf("slow S3 transaction rolled back: %+v %v", stats, err)
}
})
t.Run("fresh object with old unused metadata is preserved", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("republished", "pending", 2*time.Hour, false, true)
f.b.add(attachment.BlobKey(hash), []byte("republished"), time.Now())
stats, _, err := f.run(true, false)
if err != nil || stats.Repaired != 0 || f.status(hash) != "pending" || !f.b.has(attachment.BlobKey(hash)) {
t.Fatalf("fresh blob lost: %+v %v", stats, err)
}
})
t.Run("deep read stops at size plus one and closes body", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, true)
body := &reconcileEndless{}
f.b.opening = func(string) io.ReadCloser { return body }
stats, found, err := f.run(true, true)
if err != nil || body.read != 5 || !body.closed || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "hash_mismatch" || f.status(hash) != "ready" {
t.Fatalf("unbounded deep read: read=%d closed=%v %+v %v", body.read, body.closed, stats, err)
}
})
t.Run("deep GET outage preserves referenced state", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, true)
outage := errors.New("injected GET outage")
f.b.openErr = outage
stats, _, err := f.run(true, true)
if !errors.Is(err, outage) || stats.Repaired != 0 || f.status(hash) != "ready" {
t.Fatalf("GET outage: %+v %v", stats, err)
}
})
t.Run("valid failed object remains stable even deep", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("good", "failed", 2*time.Hour, true, true)
for _, deep := range []bool{false, true} {
stats, found, err := f.run(true, deep)
if err != nil || stats.Repaired != 0 || len(found) != 1 || found[0].Kind != "failed_present" || f.status(hash) != "failed" {
t.Fatalf("failed state unstable: %+v %v %+v", stats, err, found)
}
}
})
t.Run("dry run works with a read only PostgreSQL session", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("missing", "ready", 2*time.Hour, true, false)
cfg := f.db.Config()
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
readOnly, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer readOnly.Close()
r, err := attachment.NewReconciler(readOnly, f.b, 0)
if err != nil {
t.Fatal(err)
}
stats, err := r.Run(ctx, attachment.ReconcileOptions{Deep: true}, nil)
if err != nil || stats.Findings != 1 || stats.Repaired != 0 || f.status(hash) != "ready" {
t.Fatalf("read only dry run: %+v %v", stats, err)
}
})
t.Run("failed SQL commit after blob deletion is retryable", func(t *testing.T) {
f := reconcileSetup(t, db)
hash := f.file("unused", "pending", 2*time.Hour, false, true)
f.exec(`CREATE FUNCTION reconcile_reject_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected commit failure'; END $$`)
f.exec(`CREATE CONSTRAINT TRIGGER reconcile_reject_delete AFTER DELETE ON files DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_reject_delete()`)
t.Cleanup(func() {
f.exec(`DROP TRIGGER IF EXISTS reconcile_reject_delete ON files`)
f.exec(`DROP FUNCTION IF EXISTS reconcile_reject_delete()`)
})
stats, _, err := f.run(true, false)
if err == nil || stats.Repaired != 0 || f.status(hash) != "pending" || f.b.has(attachment.BlobKey(hash)) {
t.Fatalf("failed commit: %+v %v", stats, err)
}
f.exec(`DROP TRIGGER reconcile_reject_delete ON files`)
stats, _, err = f.run(true, false)
if err != nil || stats.Repaired != 1 || f.status(hash) != "" {
t.Fatalf("retry: %+v %v", stats, err)
}
})
}
func TestReconcilerS3(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
s3, err := testenv.StartS3(ctx)
if err != nil {
t.Fatal(err)
}
defer s3.Close()
f := reconcileSetup(t, db)
hash := f.file("good", "ready", 2*time.Hour, true, false)
missing := f.file("missing", "ready", 2*time.Hour, true, false)
key := attachment.BlobKey(hash)
if err = s3.Store.Put(ctx, key, strings.NewReader("evil"), 4, "image/png"); err != nil {
t.Fatal(err)
}
if err = s3.Store.Put(ctx, "staging/fresh", strings.NewReader("x"), 1, "image/png"); err != nil {
t.Fatal(err)
}
r, err := attachment.NewReconciler(f.db, s3.Store, 0)
if err != nil {
t.Fatal(err)
}
// Exercise the command with file-based configuration and the real listing
// identity. Its default must remain read-only, including missing metadata.
secretDir := t.TempDir()
cliEnv := os.Environ()
for name, value := range map[string]string{
"DATABASE_URL_FILE": db.DSN,
"S3_ACCESS_KEY_ID_FILE": s3.AccessKey,
"S3_SECRET_ACCESS_KEY_FILE": s3.SecretKey,
} {
path := filepath.Join(secretDir, name)
if err := os.WriteFile(path, []byte(value), 0600); err != nil {
t.Fatal(err)
}
cliEnv = append(cliEnv, name+"="+path)
}
cliEnv = append(cliEnv, "S3_ENDPOINT="+s3.Endpoint, "S3_REGION="+s3.Region, "S3_BUCKET="+s3.Bucket)
cmd := exec.CommandContext(ctx, "go", "run", "../../cmd/reconcile", "--deep")
cmd.Env = cliEnv
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
t.Fatalf("CLI dry run: %v: %s", err, stderr.String())
}
decoder := json.NewDecoder(&stdout)
var cliStats attachment.Stats
for i := 0; i < 2; i++ {
var finding attachment.Finding
if err := decoder.Decode(&finding); err != nil || finding.Applied || finding.Kind == "" || finding.Key == "" || finding.Action == "" {
t.Fatalf("CLI finding: %+v %v", finding, err)
}
}
if err := decoder.Decode(&cliStats); err != nil || cliStats.Findings != 2 || cliStats.Repaired != 0 || f.status(missing) != "ready" {
t.Fatalf("CLI mutated by default: %+v %v", cliStats, err)
}
var found []attachment.Finding
stats, err := r.Run(ctx, attachment.ReconcileOptions{Deep: true}, func(v attachment.Finding) { found = append(found, v) })
if err != nil || stats.Repaired != 0 || stats.Findings != 2 || f.status(missing) != "ready" {
t.Fatalf("S3 dry: %+v %v %+v", stats, err, found)
}
stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil)
if err != nil || stats.Repaired != 1 || f.status(missing) != "failed" || f.status(hash) != "ready" {
t.Fatalf("S3 apply: %+v %v", stats, err)
}
if _, err = s3.Store.Stat(ctx, key); err != nil {
t.Fatal("referenced corrupt object deleted", err)
}
if _, err = s3.Store.Stat(ctx, "staging/fresh"); err != nil {
t.Fatal("fresh staging deleted", err)
}
stats, err = r.Run(ctx, attachment.ReconcileOptions{Apply: true, Deep: true}, nil)
if err != nil || stats.Repaired != 0 {
t.Fatalf("S3 repeat: %+v %v", stats, err)
}
}
func TestReconcileLockRejectsMalformedHash(t *testing.T) {
if err := attachment.LockHash(context.Background(), nil, []byte("bad")); err == nil {
t.Fatal("malformed hash accepted")
}
}
+23
View File
@@ -0,0 +1,23 @@
package attachment
import (
"context"
"github.com/google/uuid"
)
type AttachmentRepository interface {
// WithPublication holds the file's hash lock through the callback and commit.
// Publication is valid only inside the callback. Any callback error rolls back.
WithPublication(ctx context.Context, attachment Attachment, fn func(Publication) error) error
GetForMember(ctx context.Context, attachmentID, actorID uuid.UUID) (Attachment, error)
}
type Publication interface {
FileReady() bool
SaveReady(ctx context.Context) error
}
type ChatMembership interface {
IsMember(ctx context.Context, chatID, actorID uuid.UUID) (bool, error)
}
+27
View File
@@ -0,0 +1,27 @@
package attachment_test
import (
"context"
"messenger/internal/testenv"
"testing"
)
func TestFilesSchemaRejectsMalformedHashes(t *testing.T) {
db, err := testenv.StartPostgres(context.Background())
if err != nil {
t.Fatal(err)
}
defer db.Close()
_, err = db.Pool.Exec(context.Background(), `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES (decode(repeat('ab',32),'hex'),12,'image/png','ready')`)
if err != nil {
t.Fatalf("valid content-addressed file: %v", err)
}
_, err = db.Pool.Exec(context.Background(), `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES ('bad',12,'image/png','ready')`)
if err == nil {
t.Fatal("accepted a malformed SHA256")
}
_, err = db.Pool.Exec(context.Background(), `INSERT INTO files(hash,size_bytes,mime_type,status) VALUES (decode(repeat('ab',32),'hex'),12,'image/png','ready')`)
if err == nil {
t.Fatal("accepted duplicate content hash")
}
}
+230
View File
@@ -0,0 +1,230 @@
package attachment
import (
"context"
"crypto/sha256"
"errors"
"io"
"log/slog"
"net/http"
"time"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
type Service struct {
attachments AttachmentRepository
chats ChatMembership
blobs Blobs
config Config
decode chan struct{}
}
type Config struct {
MaxBytes int64
MaxPixels int64
}
// A nil blobs dependency allows the text API to run without configured S3.
// Binary operations report unavailability in that mode.
func NewService(attachments AttachmentRepository, chats ChatMembership, blobs Blobs, cfg Config) *Service {
if cfg.MaxBytes == 0 {
cfg.MaxBytes = MaxUploadBytes
}
if cfg.MaxPixels == 0 {
cfg.MaxPixels = MaxImagePixels
}
return &Service{
attachments: attachments,
chats: chats,
blobs: blobs,
config: cfg,
decode: make(chan struct{}, 1),
}
}
func (s *Service) Upload(ctx context.Context, actor uuid.UUID, input UploadInput, body io.Reader) (Attachment, error) {
if err := ValidateFilename(input.Filename); err != nil {
return Attachment{}, err
}
if _, accepted := imageFormats[input.MIMEType]; !accepted {
return Attachment{}, apperr.UnsupportedMedia("only image/png and image/jpeg are accepted")
}
ok, err := s.chats.IsMember(ctx, input.ChatID, actor)
if err != nil {
return Attachment{}, err
}
if !ok {
return Attachment{}, apperr.NotFound("chat not found")
}
if input.SizeBytes > s.config.MaxBytes {
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
}
if input.SizeBytes <= 0 {
return Attachment{}, apperr.Invalid("a nonempty body with Content-Length is required")
}
if s.blobs == nil {
return Attachment{}, apperr.Unavailable("object storage is unavailable")
}
id := ident.New()
stage := "staging/" + id.String()
defer func() {
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// A failed cleanup leaves a staging object for the reconciler's grace-based collection.
if err := s.blobs.Delete(cleanup, stage); err != nil {
slog.Warn("staging cleanup deferred", "key", stage, "error", err)
}
}()
hash := sha256.New()
counter := &countReader{r: io.LimitReader(body, s.config.MaxBytes+1)}
err = s.blobs.Put(ctx, stage, io.TeeReader(counter, hash), input.SizeBytes, input.MIMEType)
if err != nil {
_, tooLarge := errors.AsType[*http.MaxBytesError](err)
if counter.n > s.config.MaxBytes || tooLarge {
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
}
if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) {
return Attachment{}, apperr.Invalid("incomplete upload")
}
return Attachment{}, unavailable(err)
}
var extra [1]byte
n, readErr := counter.Read(extra[:])
if counter.n > s.config.MaxBytes {
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
}
if counter.n != input.SizeBytes || n != 0 || !errors.Is(readErr, io.EOF) {
return Attachment{}, apperr.Invalid("body length does not match Content-Length")
}
// Full decoding is bounded by dimensions and one decoder per replica. Body
// transfer itself stays streaming and does not occupy the decoder slot.
select {
case s.decode <- struct{}{}:
case <-ctx.Done():
return Attachment{}, unavailable(ctx.Err())
}
err = s.validate(ctx, stage, input.MIMEType)
<-s.decode
if err != nil {
return Attachment{}, err
}
a := Attachment{
ID: id,
ChatID: input.ChatID,
OwnerID: actor,
Filename: input.Filename,
FileHash: hash.Sum(nil),
SizeBytes: input.SizeBytes,
MIMEType: input.MIMEType,
Status: FileReady,
CreatedAt: ident.TimeOf(id),
}
if err := s.attachments.WithPublication(ctx, a, func(p Publication) error {
if err := s.publishBlob(ctx, a, stage, p.FileReady()); err != nil {
return err
}
return p.SaveReady(ctx)
}); err != nil {
return Attachment{}, err
}
return a, nil
}
func (s *Service) publishBlob(ctx context.Context, a Attachment, stagingKey string, fileReady bool) error {
blobKey := BlobKey(a.FileHash)
if fileReady {
obj, err := s.blobs.Stat(ctx, blobKey)
if err == nil && obj.Size == a.SizeBytes {
return nil
}
if err != nil && !errors.Is(err, ErrObjectMissing) {
return unavailable(err)
}
}
// The hash is known after streaming. Copy the validated staging object to
// its permanent CAS key while the repository's publication lock is held.
if err := s.blobs.Copy(ctx, stagingKey, blobKey); err != nil {
return unavailable(err)
}
return nil
}
func (s *Service) validate(ctx context.Context, stage, mime string) (err error) {
r, err := s.blobs.Open(ctx, stage)
if err != nil {
return unavailable(err)
}
defer func() {
if closeErr := r.Close(); closeErr != nil && err == nil {
err = unavailable(closeErr)
}
}()
tracked := &storageReader{reader: r}
err = ValidateImage(tracked, mime, s.config.MaxPixels)
if tracked.err != nil {
return unavailable(tracked.err)
}
if ctx.Err() != nil {
return unavailable(ctx.Err())
}
return err
}
// Image sniffing can replace a reader failure with ErrFormat. Preserve the
// storage failure independently, while ordinary EOF still means malformed bytes.
type storageReader struct {
reader io.Reader
err error
}
func (r *storageReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if err != nil && !errors.Is(err, io.EOF) {
r.err = err
}
return n, err
}
func (s *Service) Get(ctx context.Context, actor, id uuid.UUID) (Attachment, error) {
a, err := s.attachments.GetForMember(ctx, id, actor)
if err != nil {
return Attachment{}, err
}
if a.Status != FileReady {
return Attachment{}, apperr.Conflict("attachment is not ready")
}
return a, nil
}
func (s *Service) Content(ctx context.Context, actor, id uuid.UUID) (Attachment, io.ReadCloser, error) {
a, err := s.Get(ctx, actor, id)
if err != nil {
return Attachment{}, nil, err
}
if s.blobs == nil {
return Attachment{}, nil, apperr.Unavailable("object storage is unavailable")
}
r, err := s.blobs.Open(ctx, BlobKey(a.FileHash))
if err != nil {
return Attachment{}, nil, unavailable(err)
}
return a, r, nil
}
type countReader struct {
r io.Reader
n int64
}
func (c *countReader) Read(b []byte) (int, error) {
n, err := c.r.Read(b)
c.n += int64(n)
return n, err
}
func unavailable(err error) error {
return apperr.Wrap(apperr.KindUnavailable, "object storage is unavailable", err)
}
+276
View File
@@ -0,0 +1,276 @@
package attachment_test
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"io"
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"messenger/internal/attachment"
"messenger/internal/attachment/store"
chatstore "messenger/internal/chat/store"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/testenv"
)
type testBlobs struct {
mu sync.Mutex
data map[string][]byte
copies int
failCopy bool
}
type blockingPublication struct {
*testBlobs
entered, resume chan struct{}
}
func (b *blockingPublication) Copy(ctx context.Context, from, to string) error {
close(b.entered)
select {
case <-b.resume:
case <-ctx.Done():
return ctx.Err()
}
return b.testBlobs.Copy(ctx, from, to)
}
func (b *blockingPublication) Stat(ctx context.Context, key string) (attachment.Object, error) {
o, e := b.testBlobs.Stat(ctx, key)
o.Modified = time.Now().Add(-2 * time.Hour)
return o, e
}
func TestCollectorRechecksReferencesAfterConcurrentPublication(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
actor, room := ident.New(), ident.New()
if _, err = db.Pool.Exec(ctx, `INSERT INTO users VALUES($1,'race_user','User','hash',now())`, actor); err != nil {
t.Fatal(err)
}
if _, err = db.Pool.Exec(ctx, `INSERT INTO chats VALUES($1,'race',now())`, room); err != nil {
t.Fatal(err)
}
if _, err = db.Pool.Exec(ctx, `INSERT INTO chat_members VALUES($1,$2)`, room, actor); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
hash := sha256.Sum256(data)
if _, err = db.Pool.Exec(ctx, `INSERT INTO files(hash,size_bytes,mime_type,status,created_at) VALUES($1,$2,'image/png','pending',now()-interval '2 hours')`, hash[:], len(data)); err != nil {
t.Fatal(err)
}
b := &blockingPublication{testBlobs: &testBlobs{data: map[string][]byte{}}, entered: make(chan struct{}), resume: make(chan struct{})}
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), b, attachment.Config{})
uploaded := make(chan error, 1)
go func() {
input := attachment.UploadInput{ChatID: room, Filename: "race.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
_, e := s.Upload(ctx, actor, input, bytes.NewReader(data))
uploaded <- e
}()
select {
case <-b.entered:
case <-ctx.Done():
t.Fatal("publisher never reached copy")
}
r, err := attachment.NewReconciler(db.Pool, b, time.Hour)
if err != nil {
t.Fatal(err)
}
collected := make(chan error, 1)
go func() {
stats, e := r.Run(ctx, attachment.ReconcileOptions{Apply: true}, nil)
if e == nil && stats.Repaired != 0 {
e = errors.New("collector removed a newly referenced file")
}
collected <- e
}()
// Observe a real waiting advisory lock, rather than guessing which goroutine won.
deadline := time.Now().Add(3 * time.Second)
waiting := false
for time.Now().Before(deadline) {
var n int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND NOT granted`).Scan(&n); err != nil {
t.Fatal(err)
}
if n > 0 {
waiting = true
break
}
time.Sleep(5 * time.Millisecond)
}
close(b.resume)
if !waiting {
t.Fatal("collector did not serialize with the publisher")
}
if err := <-uploaded; err != nil {
t.Fatal(err)
}
if err := <-collected; err != nil {
t.Fatal(err)
}
if _, err := b.Stat(ctx, attachment.BlobKey(hash[:])); err != nil {
t.Fatal("collector deleted published data", err)
}
}
func (b *testBlobs) Put(_ context.Context, k string, r io.Reader, n int64, m string) error {
data, err := io.ReadAll(r)
if err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
b.data[k] = data
return nil
}
func (b *testBlobs) Open(_ context.Context, k string) (io.ReadCloser, error) {
b.mu.Lock()
defer b.mu.Unlock()
data, ok := b.data[k]
if !ok {
return nil, attachment.ErrObjectMissing
}
return io.NopCloser(bytes.NewReader(data)), nil
}
func (b *testBlobs) Stat(_ context.Context, k string) (attachment.Object, error) {
b.mu.Lock()
defer b.mu.Unlock()
data, ok := b.data[k]
if !ok {
return attachment.Object{}, attachment.ErrObjectMissing
}
return attachment.Object{Key: k, Size: int64(len(data)), Modified: time.Now()}, nil
}
func (b *testBlobs) Copy(_ context.Context, from, to string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.failCopy {
return errors.New("copy outage")
}
b.copies++
b.data[to] = bytes.Clone(b.data[from])
return nil
}
func (b *testBlobs) Delete(_ context.Context, k string) error {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.data, k)
return nil
}
func (b *testBlobs) List(context.Context, string, string, int) ([]attachment.Object, error) {
return nil, nil
}
func TestUploadDeduplicatesContentButKeepsChatScopedIdentities(t *testing.T) {
ctx := context.Background()
db, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
defer db.Close()
actor, c1, c2 := ident.New(), ident.New(), ident.New()
_, err = db.Pool.Exec(ctx, `INSERT INTO users VALUES($1,'alice','Alice','hash',now());`, actor)
if err != nil {
t.Fatal(err)
}
for _, c := range []uuid.UUID{c1, c2} {
_, err = db.Pool.Exec(ctx, `INSERT INTO chats VALUES($1,'room',now())`, c)
if err != nil {
t.Fatal(err)
}
_, err = db.Pool.Exec(ctx, `INSERT INTO chat_members VALUES($1,$2)`, c, actor)
if err != nil {
t.Fatal(err)
}
}
b := &testBlobs{data: map[string][]byte{}}
s := attachment.NewService(store.NewAttachments(db.Pool), chatstore.NewChats(db.Pool), b, attachment.Config{})
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
var results [10]attachment.Attachment
var wg sync.WaitGroup
for i := range results {
wg.Go(func() {
c := c1
if i%2 == 1 {
c = c2
}
var e error
input := attachment.UploadInput{ChatID: c, Filename: "photo.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
results[i], e = s.Upload(ctx, actor, input, bytes.NewReader(data))
if e != nil {
t.Error(e)
}
})
}
wg.Wait()
var files, atts int
err = db.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM files),(SELECT count(*) FROM attachments)`).Scan(&files, &atts)
if err != nil {
t.Fatal(err)
}
if files != 1 || atts != 10 || b.copies != 1 || len(b.data) != 1 {
t.Fatalf("files=%d attachments=%d copies=%d objects=%d", files, atts, b.copies, len(b.data))
}
if results[0].ID == results[1].ID {
t.Fatal("deduplication merged chat ACL identity")
}
if _, err := s.Get(ctx, ident.New(), results[0].ID); apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("outsider got %v", err)
}
// A removed blob is republished from the new upload, preserving old references.
b.mu.Lock()
clear(b.data)
b.mu.Unlock()
input := attachment.UploadInput{ChatID: c1, Filename: "again.png", MIMEType: "image/png", SizeBytes: int64(len(data))}
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(data)); err != nil {
t.Fatal(err)
}
if b.copies != 2 {
t.Fatalf("missing ready blob was not restored: copies=%d", b.copies)
}
b.failCopy = true
other := bytes.Clone(data)
other = append(other, 0)
input.Filename, input.SizeBytes = "failed.png", int64(len(other))
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(other)); apperr.KindOf(err) != apperr.KindUnavailable {
t.Fatalf("copy outage: %v", err)
}
if len(b.data) != 1 {
t.Fatalf("failed publication left staging: %d objects", len(b.data))
}
b.failCopy = false
// S3 publication succeeds, then PostgreSQL refuses the logical attachment.
// Compensation may remove staging but must leave shared CAS data intact.
_, err = db.Pool.Exec(ctx, `CREATE FUNCTION reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected insert failure'; END $$;
CREATE TRIGGER reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION reject_attachment()`)
if err != nil {
t.Fatal(err)
}
input.Filename = "rollback.png"
if _, err := s.Upload(ctx, actor, input, bytes.NewReader(other)); err == nil {
t.Fatal("publication survived rejected metadata")
}
if len(b.data) != 2 {
t.Fatalf("expected original and recoverable orphan, got %d objects", len(b.data))
}
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM files`).Scan(&files); err != nil || files != 1 {
t.Fatalf("failed DB insert committed file metadata: %d %v", files, err)
}
}
+91
View File
@@ -0,0 +1,91 @@
package store
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/attachment"
"messenger/internal/platform/apperr"
"messenger/internal/platform/postgres"
)
type Attachments struct {
pool *pgxpool.Pool
}
var _ attachment.AttachmentRepository = (*Attachments)(nil)
func NewAttachments(pool *pgxpool.Pool) *Attachments {
return &Attachments{pool: pool}
}
// Publication and garbage collection use the same hash lock. The transaction
// spans only publication, never client transfer or image decoding.
func (r *Attachments) WithPublication(ctx context.Context, a attachment.Attachment, fn func(attachment.Publication) error) error {
return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `SET LOCAL idle_in_transaction_session_timeout = '35s'`); err != nil {
return err
}
if err := attachment.LockHash(ctx, tx, a.FileHash); err != nil {
return err
}
var status attachment.FileStatus
err := tx.QueryRow(ctx, `SELECT status FROM files WHERE hash = $1 FOR UPDATE`, a.FileHash).Scan(&status)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return err
}
return fn(publication{tx: tx, attachment: a, ready: status == attachment.FileReady})
}))
}
type publication struct {
tx pgx.Tx
attachment attachment.Attachment
ready bool
}
func (p publication) FileReady() bool { return p.ready }
func (p publication) SaveReady(ctx context.Context) error {
a := p.attachment
_, err := p.tx.Exec(ctx, `
INSERT INTO files (hash, size_bytes, mime_type, status)
VALUES ($1, $2, $3, $4)
ON CONFLICT (hash) DO UPDATE
SET size_bytes = excluded.size_bytes,
mime_type = excluded.mime_type,
status = excluded.status`,
a.FileHash, a.SizeBytes, a.MIMEType, attachment.FileReady)
if err != nil {
return fmt.Errorf("publish file: %w", err)
}
_, err = p.tx.Exec(ctx, `
INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at)
VALUES ($1, $2, $3, $4, $5, $6)`,
a.ID, a.ChatID, a.OwnerID, a.Filename, a.FileHash, a.CreatedAt)
return err
}
func (r *Attachments) GetForMember(ctx context.Context, id, actor uuid.UUID) (attachment.Attachment, error) {
var a attachment.Attachment
err := r.pool.QueryRow(ctx, `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.file_hash,
f.size_bytes, f.mime_type, f.status, a.created_at
FROM attachments a
JOIN files f ON f.hash = a.file_hash
WHERE a.id = $1 AND EXISTS (
SELECT 1 FROM chat_members m
WHERE m.chat_id = a.chat_id AND m.user_id = $2
)`, id, actor).
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.FileHash,
&a.SizeBytes, &a.MIMEType, &a.Status, &a.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return attachment.Attachment{}, apperr.NotFound("attachment not found")
}
return a, postgres.Classify(err)
}
+56
View File
@@ -0,0 +1,56 @@
package attachment
import (
"bytes"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"strings"
"unicode"
"unicode/utf8"
"messenger/internal/platform/apperr"
)
const MaxUploadBytes int64 = 10 * 1024 * 1024
const MaxImagePixels int64 = 40_000_000
var imageFormats = map[string]string{
"image/png": "png",
"image/jpeg": "jpeg",
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return apperr.Invalid("filename must contain 1-255 characters")
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return apperr.Invalid("filename contains a forbidden character")
}
}
return nil
}
// The small header is replayed into the decoder; pixels are allocated only
// after checking dimensions. The caller serializes decoding per replica.
func ValidateImage(r io.Reader, mime string, maxPixels int64) error {
limited := io.LimitReader(r, MaxUploadBytes+1)
var header bytes.Buffer
cfg, format, err := image.DecodeConfig(io.TeeReader(limited, &header))
if err != nil {
return apperr.Wrap(apperr.KindUnsupportedMedia, "invalid image", err)
}
if expectedFormat, accepted := imageFormats[mime]; !accepted || format != expectedFormat {
return apperr.UnsupportedMedia("image does not match Content-Type")
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > maxPixels/int64(cfg.Height) {
return apperr.PayloadTooLarge("image exceeds pixel limit")
}
_, _, err = image.Decode(io.MultiReader(bytes.NewReader(header.Bytes()), limited))
if err != nil {
return apperr.Wrap(apperr.KindUnsupportedMedia, "invalid image", err)
}
return nil
}
+145
View File
@@ -0,0 +1,145 @@
package attachment
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"os"
"strings"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
)
type chatMember struct {
chatID, userID uuid.UUID
}
func (m chatMember) IsMember(_ context.Context, chatID, userID uuid.UUID) (bool, error) {
return chatID == m.chatID && userID == m.userID, nil
}
func TestUploadWithoutStoragePreservesChatAccessCheck(t *testing.T) {
member := chatMember{chatID: uuid.New(), userID: uuid.New()}
s := NewService(nil, member, nil, Config{})
input := UploadInput{ChatID: member.chatID, Filename: "photo.png", MIMEType: "image/png", SizeBytes: 4}
for _, tc := range []struct {
name string
actor uuid.UUID
kind apperr.Kind
}{
{name: "member", actor: member.userID, kind: apperr.KindUnavailable},
{name: "outsider", actor: uuid.New(), kind: apperr.KindNotFound},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := s.Upload(context.Background(), tc.actor, input, strings.NewReader("data"))
if apperr.KindOf(err) != tc.kind {
t.Fatalf("got %v, want %v", err, tc.kind)
}
})
}
}
func TestValidateFilename(t *testing.T) {
for _, name := range []string{"", " ", "../a.png", `a\b.jpg`, "a\x00b", "a\nb", strings.Repeat("я", 256)} {
if err := ValidateFilename(name); apperr.KindOf(err) != apperr.KindInvalid {
t.Errorf("%q: %v", name, err)
}
}
if err := ValidateFilename("фото 👋.png"); err != nil {
t.Fatal(err)
}
}
type failingRead struct{ prefix []byte }
func (r *failingRead) Read(p []byte) (int, error) {
if len(r.prefix) > 0 {
n := copy(p, r.prefix)
r.prefix = r.prefix[n:]
return n, nil
}
return 0, errors.New("injected storage read outage")
}
type openedBlob struct {
Blobs
reader io.Reader
}
func (b openedBlob) Open(context.Context, string) (io.ReadCloser, error) {
if reader, ok := b.reader.(io.ReadCloser); ok {
return reader, nil
}
return io.NopCloser(b.reader), nil
}
type closeErrorBody struct{ io.Reader }
func (closeErrorBody) Close() error { return errors.New("injected close failure") }
func TestStagingCloseFailurePreventsPublication(t *testing.T) {
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
blobs := openedBlob{reader: closeErrorBody{Reader: bytes.NewReader(data)}}
s := NewService(nil, nil, blobs, Config{})
if err := s.validate(context.Background(), "staging/test", "image/png"); apperr.KindOf(err) != apperr.KindUnavailable {
t.Fatalf("close failure classified as %v", err)
}
}
func TestStagingReadOutageIsUnavailableBeforeAndAfterHeader(t *testing.T) {
var pngData bytes.Buffer
if err := png.Encode(&pngData, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
t.Fatal(err)
}
for _, prefix := range [][]byte{nil, pngData.Bytes()[:33]} {
s := NewService(nil, nil, openedBlob{reader: &failingRead{prefix: prefix}}, Config{})
err := s.validate(context.Background(), "staging/test", "image/png")
if apperr.KindOf(err) != apperr.KindUnavailable {
t.Fatalf("storage read error classified as %v: %v", apperr.KindOf(err), err)
}
}
}
func TestValidateImageRejectsCorruptionAndLimitsPixelsBeforeDecode(t *testing.T) {
im := image.NewNRGBA(image.Rect(0, 0, 3, 2))
im.Set(1, 1, color.NRGBA{R: 200, A: 255})
var b bytes.Buffer
if err := png.Encode(&b, im); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, mime string
data []byte
pixels int64
kind apperr.Kind
}{
{"valid", "image/png", b.Bytes(), 6, apperr.KindInternal},
{"spoof", "image/jpeg", b.Bytes(), 6, apperr.KindUnsupportedMedia},
{"truncated", "image/png", b.Bytes()[:len(b.Bytes())-20], 6, apperr.KindUnsupportedMedia},
{"pixels", "image/png", b.Bytes(), 5, apperr.KindPayloadTooLarge},
{"garbage", "image/png", []byte("not a picture"), 6, apperr.KindUnsupportedMedia},
} {
t.Run(tc.name, func(t *testing.T) {
err := ValidateImage(bytes.NewReader(tc.data), tc.mime, tc.pixels)
if tc.name == "valid" {
if err != nil {
t.Fatal(err)
}
return
}
if err == nil || apperr.KindOf(err) != tc.kind {
t.Fatalf("got %v, want kind %v", err, tc.kind)
}
})
}
}