forked from mtusi2026/mtusi2026lab6
178 lines
6.0 KiB
Go
178 lines
6.0 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"crypto/hmac"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// A ticket is authenticated, not encrypted. No user-supplied object key is accepted.
|
|
// Staging keys share the janitor's UUID namespace; they never have metadata.
|
|
type directSigner interface {
|
|
UploadMAC([]byte) []byte
|
|
PresignUpload(context.Context, string, string, int64) (string, error)
|
|
}
|
|
|
|
type DirectInput struct {
|
|
Filename string `json:"filename"`
|
|
ContentType string `json:"content_type"`
|
|
SizeBytes int64 `json:"size_bytes"`
|
|
SHA256 string `json:"sha256"`
|
|
}
|
|
|
|
type directTicket struct {
|
|
Input DirectInput
|
|
ID string
|
|
Staging string
|
|
Owner string
|
|
Chat string
|
|
Expires int64
|
|
}
|
|
|
|
type DirectUpload struct {
|
|
URL string `json:"url"`
|
|
Token string `json:"token"`
|
|
ExpiresIn int `json:"expires_in"`
|
|
Headers map[string]string `json:"headers"`
|
|
}
|
|
|
|
func (a *Attachments) InitDirect(ctx context.Context, caller, chat string, in DirectInput) (DirectUpload, error) {
|
|
chat, err := validate.CanonicalUUID("chat_id", chat)
|
|
if err != nil {
|
|
return DirectUpload{}, err
|
|
}
|
|
if _, err = a.repo.ChatByID(ctx, caller, chat); err != nil {
|
|
return DirectUpload{}, err
|
|
}
|
|
if err = validate.Filename(in.Filename); err != nil {
|
|
return DirectUpload{}, err
|
|
}
|
|
if in.ContentType != domain.ContentTypePNG && in.ContentType != domain.ContentTypeJPEG {
|
|
return DirectUpload{}, domain.ErrUnsupportedMedia
|
|
}
|
|
in.ContentType, err = parseImageType(in.ContentType)
|
|
if err != nil {
|
|
return DirectUpload{}, err
|
|
}
|
|
if in.SizeBytes > a.limits.MaxUploadBytes {
|
|
return DirectUpload{}, domain.ErrPayloadTooLarge
|
|
}
|
|
sum, err := hex.DecodeString(in.SHA256)
|
|
if in.SizeBytes <= 0 || err != nil || len(sum) != 32 {
|
|
return DirectUpload{}, domain.ErrInvalidArgument
|
|
}
|
|
in.SHA256 = strings.ToLower(in.SHA256)
|
|
signer, ok := a.objects.(directSigner)
|
|
if !ok {
|
|
return DirectUpload{}, domain.ErrUnavailable
|
|
}
|
|
ticket := directTicket{Input: in, ID: uuid.NewString(), Staging: ObjectKeyPrefix + uuid.NewString(), Owner: caller, Chat: chat, Expires: time.Now().Add(2 * time.Minute).Unix()}
|
|
data, err := json.Marshal(ticket)
|
|
if err != nil {
|
|
return DirectUpload{}, err
|
|
}
|
|
url, err := signer.PresignUpload(ctx, ticket.Staging, in.ContentType, in.SizeBytes)
|
|
if err != nil {
|
|
return DirectUpload{}, err
|
|
}
|
|
token := base64.RawURLEncoding.EncodeToString(data) + "." + base64.RawURLEncoding.EncodeToString(signer.UploadMAC(data))
|
|
return DirectUpload{URL: url, Token: token, ExpiresIn: 60, Headers: map[string]string{"Content-Type": in.ContentType}}, nil
|
|
}
|
|
|
|
func (a *Attachments) CompleteDirect(ctx context.Context, caller, chat, token string) (domain.Attachment, error) {
|
|
signer, ok := a.objects.(directSigner)
|
|
if !ok {
|
|
return domain.Attachment{}, domain.ErrUnavailable
|
|
}
|
|
parts := strings.Split(token, ".")
|
|
if len(parts) != 2 || len(token) > 4096 {
|
|
return domain.Attachment{}, domain.ErrInvalidArgument
|
|
}
|
|
data, err := base64.RawURLEncoding.DecodeString(parts[0])
|
|
if err != nil {
|
|
return domain.Attachment{}, domain.ErrInvalidArgument
|
|
}
|
|
mac, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil || !hmac.Equal(mac, signer.UploadMAC(data)) {
|
|
return domain.Attachment{}, domain.ErrInvalidArgument
|
|
}
|
|
var t directTicket
|
|
if json.Unmarshal(data, &t) != nil {
|
|
return domain.Attachment{}, domain.ErrInvalidArgument
|
|
}
|
|
if t.Owner != caller || t.Chat != chat {
|
|
return domain.Attachment{}, domain.ErrNotFound
|
|
}
|
|
if _, err := a.repo.ChatByID(ctx, caller, chat); err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
// Retry is idempotent, including a retry after an uncertain database COMMIT.
|
|
if att, err := a.repo.AttachmentForMember(ctx, caller, t.ID); err == nil {
|
|
return att, nil
|
|
} else if !errors.Is(err, domain.ErrNotFound) {
|
|
return domain.Attachment{}, err
|
|
}
|
|
if time.Now().Unix() >= t.Expires {
|
|
return domain.Attachment{}, domain.ErrConflict
|
|
}
|
|
select {
|
|
case a.uploads <- struct{}{}:
|
|
defer func() { <-a.uploads }()
|
|
default:
|
|
return domain.Attachment{}, domain.ErrRateLimited
|
|
}
|
|
body, size, err := a.objects.Get(ctx, t.Staging)
|
|
if errors.Is(err, objectstore.ErrNotFound) {
|
|
return domain.Attachment{}, domain.ErrConflict
|
|
}
|
|
if err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
defer body.Close()
|
|
if size != t.Input.SizeBytes {
|
|
return domain.Attachment{}, domain.ErrInvalidArgument
|
|
}
|
|
file, actual, sum, err := a.spoolBody(body)
|
|
if err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
defer file.Close()
|
|
if actual != size || sum != t.Input.SHA256 {
|
|
return domain.Attachment{}, domain.ErrInvalidArgument
|
|
}
|
|
if err = a.checkImage(ctx, file, t.Input.ContentType); err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
|
return domain.Attachment{}, domain.ErrUnavailable
|
|
}
|
|
// A unique permanent key per attempt prevents a concurrent failed attempt from
|
|
// deleting an object saved by another complete. Clients can write only staging.
|
|
att := domain.Attachment{ID: t.ID, ChatID: chat, OwnerID: caller, Filename: t.Input.Filename, ContentType: t.Input.ContentType, SizeBytes: size, SHA256: sum, ObjectKey: ObjectKeyPrefix + uuid.NewString(), Status: domain.StatusReady}
|
|
if err = a.objects.Put(ctx, att.ObjectKey, att.ContentType, file, size); err != nil {
|
|
return domain.Attachment{}, err
|
|
}
|
|
saved, err := a.repo.CreateAttachment(ctx, att)
|
|
if err != nil {
|
|
// Leave unreferenced keys to the janitor: an uncertain COMMIT must not delete data.
|
|
if existing, lookup := a.repo.AttachmentForMember(ctx, caller, t.ID); lookup == nil {
|
|
return existing, nil
|
|
}
|
|
return domain.Attachment{}, err
|
|
}
|
|
// Keep staging until expiry/grace: deleting while its PUT URL is valid allows
|
|
// recreation anyway. The janitor reclaims abandoned and completed staging alike.
|
|
return saved, nil
|
|
}
|