Files
mtusi2026lab5/internal/service/attachment/service.go
T
Vladislav Kunetskiy e40a5cf215 lab5: ограничение одновременных upload-spool и evidence после ревью
Process-level semaphore bounds temporary disk use on the upload path; refresh raw evidence after the review fixes.
2026-10-30 23:16:12 +03:00

710 lines
21 KiB
Go

package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"regexp"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"golang.org/x/sync/semaphore"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/imagecheck"
"mtusi-messenger/internal/platform/objectstore"
)
const (
contentTypePNG = "image/png"
contentTypeJPEG = "image/jpeg"
objectPrefixAttachments = domain.AttachmentsPrefix
objectPrefixStaging = domain.StagingUploadPrefix
objectPrefixPresign = domain.StagingPresignPrefix
)
var sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
// Repository is the persistence port. It is consumer-side so the service can be
// tested without PostgreSQL. Job/outbox writes are atomic with the attachment
// row inside CreateQueued/CompletePresign.
type Repository interface {
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)
GetVariant(
ctx context.Context,
attachmentID uuid.UUID,
pipelineVersion int,
name domain.VariantName,
) (domain.Variant, error)
CreateQueued(
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CompletePresign(
ctx context.Context,
ownerID, attachmentID uuid.UUID,
verifiedKey, finalKey string,
pipelineVersion, maxAttempts int,
jobID uuid.UUID,
) (domain.Attachment, error)
Admission(ctx context.Context, ownerID uuid.UUID) (userPending, totalPending int, stagedBytes int64, err error)
DeletePending(ctx context.Context, id uuid.UUID) error
}
// Config carries attachment limits and the shared job contract knobs.
type Config struct {
MaxUploadBytes int64
MaxImagePixels int64
PresignTTL time.Duration
PipelineVersion int
MaxAttempts int
MaxPendingPerUser int
MaxPending int
MaxStagedBytes int64
MaxConcurrent int
}
type Service struct {
repo Repository
store objectstore.Store
config Config
log *slog.Logger
upload *semaphore.Weighted
}
func NewService(repo Repository, store objectstore.Store, config Config, log *slog.Logger) *Service {
if log == nil {
log = slog.Default()
}
service := &Service{repo: repo, store: store, config: config, log: log}
if config.MaxConcurrent > 0 {
service.upload = semaphore.NewWeighted(int64(config.MaxConcurrent))
}
return service
}
// UploadInput is one raw-body upload. DeclaredContentType comes from the HTTP
// Content-Type header and is cross-checked against the detected format.
type UploadInput struct {
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
DeclaredContentType string
Body io.Reader
}
// Upload durably stages the original, records the job intent and returns the
// queued snapshot. It never waits for the broker or the worker.
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
if s.upload != nil {
if err := s.upload.Acquire(ctx, 1); err != nil {
return domain.Attachment{}, unavailable("acquire upload slot", err)
}
defer s.upload.Release(1)
}
if err := ValidateFilename(input.Filename); err != nil {
return domain.Attachment{}, err
}
member, err := s.repo.IsChatMember(ctx, input.ChatID, input.OwnerID)
if err != nil {
return domain.Attachment{}, err
}
if !member {
return domain.Attachment{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
}
userPending, totalPending, stagedBytes, err := s.repo.Admission(ctx, input.OwnerID)
if err != nil {
return domain.Attachment{}, unavailable("check admission", err)
}
if (s.config.MaxPendingPerUser > 0 && userPending >= s.config.MaxPendingPerUser) ||
(s.config.MaxPending > 0 && totalPending >= s.config.MaxPending) ||
(s.config.MaxStagedBytes > 0 && stagedBytes >= s.config.MaxStagedBytes) {
return domain.Attachment{}, fmt.Errorf("%w: too many unfinished uploads", domain.ErrRateLimited)
}
file, size, sum, err := s.spool(input.Body)
if err != nil {
return domain.Attachment{}, err
}
defer func() { _ = file.Close() }()
defer func() { _ = os.Remove(file.Name()) }()
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
}
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
if err != nil {
return domain.Attachment{}, mapImageError(err)
}
if info.ContentType != input.DeclaredContentType {
return domain.Attachment{}, fmt.Errorf(
"%w: declared %q, detected %q",
domain.ErrUnsupportedMedia, input.DeclaredContentType, info.ContentType,
)
}
id, err := uuid.NewV7()
if err != nil {
return domain.Attachment{}, fmt.Errorf("generate attachment id: %w", err)
}
jobID, err := uuid.NewV7()
if err != nil {
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
}
stagingKey := domain.StagingUploadKey(input.ChatID, id)
finalKey := domain.OriginalObjectKey(input.ChatID, id)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
}
if err := s.store.Put(ctx, stagingKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("store staging object", err)
}
if err := s.verifyStaging(ctx, stagingKey, size, sum); err != nil {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, unavailable("verify staging object", err)
}
job := domain.Job{
ID: jobID,
AttachmentID: id,
PipelineVersion: s.config.PipelineVersion,
SourceKey: stagingKey,
Attempt: 1,
MaxAttempts: s.config.MaxAttempts,
CreatedAt: time.Now().UTC(),
}
limits := s.admissionLimits()
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
OwnerID: input.OwnerID,
ObjectKey: finalKey,
StagingKey: stagingKey,
Filename: input.Filename,
ContentType: info.ContentType,
SizeBytes: size,
SHA256: sum,
Status: domain.AttachmentQueued,
PipelineVersion: s.config.PipelineVersion,
}, job, limits)
if err != nil {
if errors.Is(err, domain.ErrRateLimited) {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, err
}
// An ambiguous COMMIT may have persisted the intent; leave the staging
// object for the sweeper instead of destroying a queued job's source.
return domain.Attachment{}, unavailable("commit attachment intent", err)
}
created.Variants = []domain.Variant{}
return created, nil
}
// Get returns metadata for any public status. Variants are exposed only for the
// currently published pipeline version and only when ready.
func (s *Service) Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
return domain.Attachment{}, err
}
if !attachment.Status.Public() {
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
}
return s.withVariants(ctx, attachment)
}
// OpenVariant returns metadata plus the selected content stream. Only a ready
// attachment has bytes.
func (s *Service) OpenVariant(
ctx context.Context,
callerID, id uuid.UUID,
name domain.VariantName,
) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
if !attachment.Status.Public() || attachment.Status != domain.AttachmentReady {
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
"%w: attachment is %s", domain.ErrConflict, attachment.Status,
)
}
if name == "" || name == domain.VariantOriginal {
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
return attachment, domain.Variant{
Name: domain.VariantOriginal,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
SHA256: attachment.SHA256,
ObjectKey: attachment.ObjectKey,
}, body, nil
}
if !name.Valid() {
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
"%w: variant %q", domain.ErrValidation, name,
)
}
variant, err := s.repo.GetVariant(ctx, attachment.ID, attachment.PipelineVersion, name)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
body, _, err := s.store.Open(ctx, variant.ObjectKey)
if err != nil {
return domain.Attachment{}, domain.Variant{}, nil, err
}
return attachment, variant, body, nil
}
// Open is kept for the legacy service port used by tests.
func (s *Service) Open(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error) {
attachment, _, body, err := s.OpenVariant(ctx, callerID, id, domain.VariantOriginal)
return attachment, body, err
}
func (s *Service) withVariants(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error) {
attachment.Variants = []domain.Variant{}
if attachment.Status != domain.AttachmentReady {
return attachment, nil
}
variants, err := s.repo.ListVariants(ctx, attachment.ID, attachment.PipelineVersion)
if err != nil {
return domain.Attachment{}, err
}
if variants != nil {
attachment.Variants = variants
}
return attachment, nil
}
func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
if err := ValidateFilename(request.Filename); err != nil {
return domain.PresignResult{}, err
}
if request.ContentType != contentTypePNG && request.ContentType != contentTypeJPEG {
return domain.PresignResult{}, fmt.Errorf("%w: content type %q", domain.ErrUnsupportedMedia, request.ContentType)
}
if request.SizeBytes < 1 {
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrValidation, request.SizeBytes)
}
if request.SizeBytes > s.config.MaxUploadBytes {
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrTooLarge, request.SizeBytes)
}
if !sha256Pattern.MatchString(request.SHA256) {
return domain.PresignResult{}, fmt.Errorf("%w: sha256 must be 64 lowercase hex characters", domain.ErrValidation)
}
member, err := s.repo.IsChatMember(ctx, request.ChatID, request.OwnerID)
if err != nil {
return domain.PresignResult{}, err
}
if !member {
return domain.PresignResult{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
}
id, err := uuid.NewV7()
if err != nil {
return domain.PresignResult{}, fmt.Errorf("generate attachment id: %w", err)
}
stagingKey := objectPrefixPresign + request.ChatID.String() + "/" + id.String()
if _, err := s.repo.CreatePresign(ctx, domain.AttachmentDraft{
ID: id,
ChatID: request.ChatID,
OwnerID: request.OwnerID,
ObjectKey: stagingKey,
StagingKey: stagingKey,
Filename: request.Filename,
ContentType: request.ContentType,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
Status: domain.AttachmentPending,
PipelineVersion: s.config.PipelineVersion,
}, s.admissionLimits()); err != nil {
return domain.PresignResult{}, err
}
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, request.SizeBytes, s.config.PresignTTL)
if err != nil {
s.cleanupPending(ctx, id, "")
return domain.PresignResult{}, unavailable("presign attachment", err)
}
return domain.PresignResult{
AttachmentID: id,
UploadURL: url,
ExpiresAt: expiresAt,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
}, nil
}
// Complete verifies the presigned object, copies the verified bytes to a
// server-owned staging key, and enqueues the same async pipeline as the proxy
// upload. The client's staging key remains writable until the verified copy is
// durable.
func (s *Service) Complete(
ctx context.Context,
ownerID, id uuid.UUID,
requestSHA string,
) (domain.Attachment, error) {
if !sha256Pattern.MatchString(requestSHA) {
return domain.Attachment{}, fmt.Errorf("%w: sha256 must be 64 lowercase hex characters", domain.ErrValidation)
}
attachment, err := s.repo.GetForOwner(ctx, ownerID, id)
if err != nil {
return domain.Attachment{}, err
}
switch attachment.Status {
case domain.AttachmentReady, domain.AttachmentQueued, domain.AttachmentProcessing:
if attachment.SHA256 != requestSHA {
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
}
return s.withVariants(ctx, attachment)
case domain.AttachmentFailed:
return domain.Attachment{}, fmt.Errorf("%w: attachment is failed", domain.ErrConflict)
case domain.AttachmentPending:
default:
return domain.Attachment{}, fmt.Errorf("%w: unknown attachment status", domain.ErrConflict)
}
if !strings.HasPrefix(attachment.ObjectKey, objectPrefixPresign) {
return domain.Attachment{}, fmt.Errorf("%w: attachment is not a presigned upload", domain.ErrConflict)
}
head, err := s.store.Head(ctx, attachment.ObjectKey)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return domain.Attachment{}, fmt.Errorf("%w: object was not uploaded", domain.ErrIncomplete)
}
return domain.Attachment{}, err
}
if head.Size != attachment.SizeBytes {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf(
"%w: uploaded %d bytes, declared %d",
domain.ErrValidation, head.Size, attachment.SizeBytes,
)
}
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
if err != nil {
return domain.Attachment{}, err
}
file, size, sum, err := s.spool(body)
_ = body.Close()
if err != nil {
return domain.Attachment{}, err
}
defer func() { _ = file.Close() }()
defer func() { _ = os.Remove(file.Name()) }()
if size != attachment.SizeBytes {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf("%w: uploaded object size changed", domain.ErrValidation)
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind uploaded object: %w", err)
}
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
if err != nil {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, mapImageError(err)
}
if info.ContentType != attachment.ContentType {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf(
"%w: declared %q, detected %q",
domain.ErrUnsupportedMedia, attachment.ContentType, info.ContentType,
)
}
if sum != attachment.SHA256 {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf("%w: uploaded object checksum mismatch", domain.ErrValidation)
}
if requestSHA != attachment.SHA256 {
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
}
verifiedKey := domain.StagingVerifiedKey(attachment.ChatID, attachment.ID)
finalKey := domain.OriginalObjectKey(attachment.ChatID, attachment.ID)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind verified object: %w", err)
}
if err := s.store.Put(ctx, verifiedKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("store verified object", err)
}
if err := s.verifyStaging(ctx, verifiedKey, size, sum); err != nil {
s.deleteObject(ctx, id, verifiedKey)
return domain.Attachment{}, unavailable("verify staging object", err)
}
jobID, err := uuid.NewV7()
if err != nil {
s.deleteObject(ctx, id, verifiedKey)
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
}
queued, err := s.repo.CompletePresign(
ctx, ownerID, id, verifiedKey, finalKey,
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
)
if err != nil {
// The verified key is shared by concurrent completions of this
// attachment. Never delete it here: a winning request may already have
// queued a job pointing at it. The orphan sweeper owns abandoned keys.
if errors.Is(err, domain.ErrConflict) {
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.SHA256 == requestSHA && current.Status.Public() {
return s.withVariants(ctx, current)
}
return domain.Attachment{}, fmt.Errorf("%w: attachment is no longer pending", domain.ErrConflict)
}
return domain.Attachment{}, unavailable("commit presigned attachment", err)
}
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "presign staging cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
queued.Variants = []domain.Variant{}
return queued, nil
}
// verifyStaging checks the freshly written object; a mismatch is a broken
// staging handoff and must never become a 202.
func (s *Service) admissionLimits() domain.AdmissionLimits {
return domain.AdmissionLimits{
PerUser: s.config.MaxPendingPerUser,
Total: s.config.MaxPending,
Bytes: s.config.MaxStagedBytes,
}
}
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
head, err := s.store.Head(ctx, key)
if err != nil {
return fmt.Errorf("head staging object: %w", err)
}
if head.Size != size {
return fmt.Errorf("staging size %d, want %d", head.Size, size)
}
if sha := head.Metadata["sha256"]; sha != "" && sha != sum {
return errors.New("staging checksum metadata does not match")
}
return nil
}
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
file, err := os.CreateTemp("", "lab5-upload-*")
if err != nil {
return nil, 0, "", fmt.Errorf("create upload spool: %w", err)
}
cleanup := func() {
_ = file.Close()
_ = os.Remove(file.Name())
}
hasher := sha256.New()
limited := io.LimitReader(body, s.config.MaxUploadBytes+1)
buffer := make([]byte, 32<<10)
size, err := io.CopyBuffer(io.MultiWriter(file, hasher), limited, buffer)
if err != nil {
cleanup()
var maxBytes *http.MaxBytesError
if errors.As(err, &maxBytes) {
return nil, 0, "", fmt.Errorf("%w: request body exceeds %d bytes", domain.ErrTooLarge, s.config.MaxUploadBytes)
}
return nil, 0, "", fmt.Errorf("%w: read upload: %w", domain.ErrValidation, err)
}
if size > s.config.MaxUploadBytes {
cleanup()
return nil, 0, "", fmt.Errorf("%w: upload exceeds %d bytes", domain.ErrTooLarge, s.config.MaxUploadBytes)
}
if size == 0 {
cleanup()
return nil, 0, "", fmt.Errorf("%w: empty image", domain.ErrUnsupportedMedia)
}
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
}
func (s *Service) deleteObject(ctx context.Context, id uuid.UUID, key string) {
if key == "" {
return
}
if err := s.store.Delete(ctx, key); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "object cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
}
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
s.deleteObject(ctx, id, objectKey)
if err := s.repo.DeletePending(ctx, id); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "pending attachment cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
}
// ValidateFilename implements the contract rule: 1-255 Unicode code points,
// no path separators, NUL or control characters. The name is display-only; the
// S3 key is always generated.
func ValidateFilename(name string) error {
if !utf8.ValidString(name) {
return fmt.Errorf("%w: filename is not valid UTF-8", domain.ErrValidation)
}
length := utf8.RuneCountInString(name)
if length < 1 || length > 255 {
return fmt.Errorf("%w: filename length is %d, want 1-255 code points", domain.ErrValidation, length)
}
if strings.TrimSpace(name) == "" {
return fmt.Errorf("%w: filename consists of whitespace only", domain.ErrValidation)
}
if strings.ContainsAny(name, "/\\\x00") {
return fmt.Errorf("%w: filename contains a path separator or NUL", domain.ErrValidation)
}
for _, r := range name {
if unicode.IsControl(r) {
return fmt.Errorf("%w: filename contains a control character", domain.ErrValidation)
}
}
return nil
}
func mapImageError(err error) error {
switch {
case errors.Is(err, imagecheck.ErrTooLarge):
return fmt.Errorf("%w: %w", domain.ErrTooLarge, err)
case errors.Is(err, imagecheck.ErrUnsupported), errors.Is(err, imagecheck.ErrCorrupt):
return fmt.Errorf("%w: %w", domain.ErrUnsupportedMedia, err)
default:
return err
}
}
func unavailable(operation string, err error) error {
if errors.Is(err, domain.ErrUnavailable) || errors.Is(err, domain.ErrNotFound) {
return err
}
return fmt.Errorf("%w: %s: %w", domain.ErrUnavailable, operation, err)
}