496 lines
15 KiB
Go
496 lines
15 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"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/imagecheck"
|
|
"mtusi-messenger/internal/platform/objectstore"
|
|
)
|
|
|
|
const (
|
|
contentTypePNG = "image/png"
|
|
contentTypeJPEG = "image/jpeg"
|
|
|
|
objectPrefixAttachments = "attachments/"
|
|
objectPrefixStaging = "staging/"
|
|
objectPrefixPresign = "staging/presign/"
|
|
)
|
|
|
|
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.
|
|
type Repository interface {
|
|
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
|
Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
|
|
MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)
|
|
DeletePending(ctx context.Context, id uuid.UUID) error
|
|
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
|
|
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
|
|
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
|
|
ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)
|
|
ListKeys(ctx context.Context, limit, offset int32) ([]domain.AttachmentKey, error)
|
|
}
|
|
|
|
// Config carries the attachment limits. They are validated by config.Load.
|
|
type Config struct {
|
|
MaxUploadBytes int64
|
|
MaxImagePixels int64
|
|
PresignTTL time.Duration
|
|
}
|
|
|
|
type Service struct {
|
|
repo Repository
|
|
store objectstore.Store
|
|
config Config
|
|
log *slog.Logger
|
|
}
|
|
|
|
func NewService(repo Repository, store objectstore.Store, config Config, log *slog.Logger) *Service {
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
|
|
return &Service{repo: repo, store: store, config: config, log: log}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
|
|
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)
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
objectKey := objectPrefixAttachments + input.ChatID.String() + "/" + id.String()
|
|
|
|
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
|
|
ID: id,
|
|
ChatID: input.ChatID,
|
|
OwnerID: input.OwnerID,
|
|
ObjectKey: objectKey,
|
|
Filename: input.Filename,
|
|
ContentType: info.ContentType,
|
|
SizeBytes: size,
|
|
SHA256: sum,
|
|
}); err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
|
|
}
|
|
|
|
if err := s.store.Put(ctx, objectKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
|
s.cleanupPending(ctx, id, "")
|
|
|
|
return domain.Attachment{}, unavailable("store attachment", err)
|
|
}
|
|
|
|
ready, err := s.repo.MarkReady(ctx, id, objectKey)
|
|
if err != nil {
|
|
// The object and the pending row remain; the sweeper either finalises
|
|
// the row or removes both after the grace period. The client must not
|
|
// receive 201 until metadata is committed.
|
|
return domain.Attachment{}, unavailable("commit attachment", err)
|
|
}
|
|
|
|
return ready, nil
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
// Contract 1.4.0 declares Attachment.status as the single value "ready".
|
|
// Pending/failed rows therefore cannot be represented in a 200 response;
|
|
// they are reported as 409 until lab5 extends the enum.
|
|
if attachment.Status != domain.AttachmentReady {
|
|
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
|
}
|
|
|
|
return attachment, nil
|
|
}
|
|
|
|
// Open returns metadata and the original stream. Only ready attachments have
|
|
// bytes; pending/failed return 409 on the content endpoint.
|
|
func (s *Service) Open(
|
|
ctx context.Context,
|
|
callerID, id uuid.UUID,
|
|
) (domain.Attachment, io.ReadCloser, error) {
|
|
attachment, err := s.repo.GetForMember(ctx, callerID, id)
|
|
if err != nil {
|
|
return domain.Attachment{}, nil, err
|
|
}
|
|
|
|
if attachment.Status != domain.AttachmentReady {
|
|
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
|
}
|
|
|
|
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
|
|
if err != nil {
|
|
return domain.Attachment{}, nil, err
|
|
}
|
|
|
|
return attachment, body, 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.Create(ctx, domain.AttachmentDraft{
|
|
ID: id,
|
|
ChatID: request.ChatID,
|
|
OwnerID: request.OwnerID,
|
|
ObjectKey: stagingKey,
|
|
Filename: request.Filename,
|
|
ContentType: request.ContentType,
|
|
SizeBytes: request.SizeBytes,
|
|
SHA256: request.SHA256,
|
|
}); 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
|
|
}
|
|
|
|
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:
|
|
if attachment.SHA256 != requestSHA {
|
|
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
|
|
}
|
|
|
|
return attachment, nil
|
|
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
|
|
}
|
|
|
|
hasher := sha256.New()
|
|
info, validateErr := imagecheck.Validate(io.TeeReader(body, hasher), s.config.MaxImagePixels)
|
|
closeErr := body.Close()
|
|
|
|
if validateErr != nil {
|
|
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
|
|
|
return domain.Attachment{}, mapImageError(validateErr)
|
|
}
|
|
|
|
if closeErr != nil {
|
|
return domain.Attachment{}, unavailable("read uploaded object", closeErr)
|
|
}
|
|
|
|
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,
|
|
)
|
|
}
|
|
|
|
sum := hex.EncodeToString(hasher.Sum(nil))
|
|
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 {
|
|
// The object is valid; only the completion request is inconsistent.
|
|
// Keep the pending row and staging object so a retry can succeed.
|
|
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
|
|
}
|
|
|
|
finalKey := objectPrefixAttachments + attachment.ChatID.String() + "/" + id.String()
|
|
|
|
if err := s.store.Copy(ctx, attachment.ObjectKey, finalKey, attachment.ContentType, map[string]string{"sha256": sum}); err != nil {
|
|
return domain.Attachment{}, unavailable("publish attachment", err)
|
|
}
|
|
|
|
ready, err := s.repo.MarkReady(ctx, id, finalKey)
|
|
if err != nil {
|
|
// A concurrent completion may have won. Re-read instead of reporting a
|
|
// spurious failure.
|
|
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
|
|
if getErr == nil && current.Status == domain.AttachmentReady && current.SHA256 == requestSHA {
|
|
return current, nil
|
|
}
|
|
|
|
return domain.Attachment{}, unavailable("commit attachment", err)
|
|
}
|
|
|
|
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil {
|
|
// The final object is already committed; a stale staging object is an
|
|
// orphan and the sweeper removes it after the grace period.
|
|
s.log.WarnContext(ctx, "staging object cleanup failed",
|
|
slog.String("attachment_id", id.String()),
|
|
slog.Any("error", err),
|
|
)
|
|
}
|
|
|
|
return ready, nil
|
|
}
|
|
|
|
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
|
|
file, err := os.CreateTemp("", "lab4-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) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
|
|
if objectKey != "" {
|
|
if err := s.store.Delete(ctx, objectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
|
s.log.WarnContext(ctx, "object cleanup failed",
|
|
slog.String("attachment_id", id.String()),
|
|
slog.Any("error", err),
|
|
)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|