Добавьте S3-вложения с дедупликацией и безопасной сверкой хранилищ
This commit is contained in:
@@ -0,0 +1,172 @@
|
||||
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 {
|
||||
repo Repository
|
||||
blobs Blobs
|
||||
maxBytes, maxPixels int64
|
||||
decode chan struct{}
|
||||
}
|
||||
|
||||
func NewService(repo Repository, blobs Blobs, maxBytes, maxPixels int64) *Service {
|
||||
if maxBytes == 0 {
|
||||
maxBytes = MaxUploadBytes
|
||||
}
|
||||
if maxPixels == 0 {
|
||||
maxPixels = MaxImagePixels
|
||||
}
|
||||
return &Service{repo: repo, blobs: blobs, maxBytes: maxBytes, maxPixels: maxPixels, decode: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
func (s *Service) Upload(ctx context.Context, actor, chatID uuid.UUID, filename, mime string, size int64, body io.Reader) (Attachment, error) {
|
||||
if err := ValidateFilename(filename); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if mime != "image/png" && mime != "image/jpeg" {
|
||||
return Attachment{}, apperr.UnsupportedMedia("only image/png and image/jpeg are accepted")
|
||||
}
|
||||
ok, err := s.repo.IsMember(ctx, chatID, actor)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if !ok {
|
||||
return Attachment{}, apperr.NotFound("chat not found")
|
||||
}
|
||||
if size > s.maxBytes {
|
||||
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
|
||||
}
|
||||
if size <= 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()
|
||||
if err := s.blobs.Delete(cleanup, stage); err != nil {
|
||||
slog.Warn("staging cleanup deferred", "error", err)
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
counter := &countReader{r: io.LimitReader(body, s.maxBytes+1)}
|
||||
err = s.blobs.Put(ctx, stage, io.TeeReader(counter, hash), size, mime)
|
||||
if err != nil {
|
||||
_, tooLarge := errors.AsType[*http.MaxBytesError](err)
|
||||
if counter.n > s.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.maxBytes {
|
||||
return Attachment{}, apperr.PayloadTooLarge("file exceeds byte limit")
|
||||
}
|
||||
if counter.n != size || 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, mime)
|
||||
<-s.decode
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
a := Attachment{ID: id, ChatID: chatID, OwnerID: actor, Filename: filename, FileHash: hash.Sum(nil), SizeBytes: size, MIMEType: mime, Status: "ready", CreatedAt: ident.TimeOf(id)}
|
||||
if err := s.repo.Publish(ctx, a, stage); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *Service) validate(ctx context.Context, stage, mime string) error {
|
||||
r, err := s.blobs.Open(ctx, stage)
|
||||
if err != nil {
|
||||
return unavailable(err)
|
||||
}
|
||||
defer r.Close()
|
||||
tracked := &storageReader{reader: r}
|
||||
err = ValidateImage(tracked, mime, s.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.repo.GetForMember(ctx, id, actor)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
if a.Status != "ready" {
|
||||
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, e := c.r.Read(b); c.n += int64(n); return n, e }
|
||||
func unavailable(err error) error {
|
||||
return apperr.Wrap(apperr.KindUnavailable, "object storage is unavailable", err)
|
||||
}
|
||||
Reference in New Issue
Block a user