forked from mtusi2026/mtusi2026lab6
ЛР 6 — БПИ2302 — Нурлыгаянова — на 3
This commit is contained in:
@@ -0,0 +1,290 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/imagecheck"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var _ AttachmentsService = (*Attachments)(nil)
|
||||
|
||||
// ObjectKeyPrefix — префикс ключей оригиналов. Очиститель обходит только его.
|
||||
const ObjectKeyPrefix = "originals/"
|
||||
|
||||
// Предел на компенсирующее удаление объекта, когда запись метаданных не удалась.
|
||||
const compensationTimeout = 5 * time.Second
|
||||
|
||||
type AttachmentLimits struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
MaxConcurrentUploads int
|
||||
}
|
||||
|
||||
type attachmentRepo interface {
|
||||
store.ChatStore
|
||||
store.AttachmentStore
|
||||
}
|
||||
|
||||
type Attachments struct {
|
||||
repo attachmentRepo
|
||||
objects objectstore.Store
|
||||
limits AttachmentLimits
|
||||
checker *imagecheck.Checker
|
||||
// uploads — слоты загрузок. Вместе с лимитом размера они ограничивают диск реплики под временные
|
||||
// файлы; память на одну загрузку от размера файла не зависит.
|
||||
uploads chan struct{}
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewAttachments(repo attachmentRepo, objects objectstore.Store, limits AttachmentLimits, logger *slog.Logger) *Attachments {
|
||||
return &Attachments{
|
||||
repo: repo,
|
||||
objects: objects,
|
||||
limits: limits,
|
||||
checker: imagecheck.New(limits.MaxImagePixels),
|
||||
uploads: make(chan struct{}, limits.MaxConcurrentUploads),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Upload выполняет проверки от дешёвых к дорогим: доступ, параметры, заявленный размер и только
|
||||
// потом чтение тела. Тело идёт потоком во временный файл, из него в декодер и в S3, поэтому в памяти
|
||||
// файл целиком не лежит. Порядок записи: сначала объект, затем метаданные, поэтому строка в БД
|
||||
// ссылается на устойчивый staging; 202 означает сохранённый оригинал и намерение обработки.
|
||||
func (a *Attachments) Upload(ctx context.Context, in UploadInput) (domain.Attachment, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", in.ChatID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := a.repo.ChatByID(ctx, in.CallerID, chatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := validate.Filename(in.Filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
declared, err := parseImageType(in.ContentType)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if in.ContentLength > a.limits.MaxUploadBytes {
|
||||
return domain.Attachment{}, domain.ErrPayloadTooLarge
|
||||
}
|
||||
|
||||
select {
|
||||
case a.uploads <- struct{}{}:
|
||||
defer func() { <-a.uploads }()
|
||||
default:
|
||||
return domain.Attachment{}, domain.ErrRateLimited
|
||||
}
|
||||
|
||||
spool, size, sum, err := a.spoolBody(in.Body)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
defer spool.Close()
|
||||
|
||||
if err := a.checkImage(ctx, spool, declared); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := spool.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
att := domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: in.CallerID,
|
||||
Filename: in.Filename,
|
||||
ContentType: declared,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
ObjectKey: "staging/" + id,
|
||||
Status: domain.StatusQueued,
|
||||
}
|
||||
if err := a.objects.Put(ctx, att.ObjectKey, att.ContentType, spool, size); err != nil {
|
||||
// Объект мог успеть сохраниться. Удалять его здесь бессмысленно: при недоступном S3 удаление
|
||||
// тоже не пройдёт, а клиент лишние секунды ждал бы ответа. Его уберёт очиститель.
|
||||
a.logger.Warn("attachment object put failed", slog.Any("err", err))
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
saved, err := a.repo.CreateAttachment(ctx, att)
|
||||
if err != nil {
|
||||
a.compensate(ctx, att)
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
// checkImage сравнивает заявленный тип с настоящим до декодирования: подмена типа не тратит память.
|
||||
func (a *Attachments) checkImage(ctx context.Context, file io.ReadSeeker, declared string) error {
|
||||
detected, err := a.checker.Inspect(file)
|
||||
if err == nil && detected != declared {
|
||||
return domain.ErrUnsupportedMedia
|
||||
}
|
||||
if err == nil {
|
||||
err = a.checker.Decode(ctx, file)
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, imagecheck.ErrTooManyPixels):
|
||||
return domain.ErrPayloadTooLarge
|
||||
case errors.Is(err, imagecheck.ErrUnsupported):
|
||||
return domain.ErrUnsupportedMedia
|
||||
case errors.Is(err, imagecheck.ErrBusy):
|
||||
return domain.ErrRateLimited
|
||||
}
|
||||
return fmt.Errorf("%w: image check: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
// compensate убирает объект, для которого метаданные не сохранились. Контекст отвязан от запроса:
|
||||
// клиент мог уже отключиться. Удалять можно, только убедившись, что строки нет: ошибка INSERT не
|
||||
// доказывает отсутствие записи (COMMIT мог пройти, а ответ потеряться), и удаление оставило бы
|
||||
// подтверждённую строку без файла. Если проверить нельзя, объект остаётся очистителю: он удаляет
|
||||
// только объекты без строки и только после grace period (cmd/janitor).
|
||||
func (a *Attachments) compensate(ctx context.Context, att domain.Attachment) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), compensationTimeout)
|
||||
defer cancel()
|
||||
exists, err := a.repo.AttachmentExists(ctx, att.ID)
|
||||
if err != nil {
|
||||
a.logger.Warn("orphan check failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
a.logger.Warn("metadata write reported an error but the row exists, object is kept", slog.String("attachment_id", att.ID))
|
||||
return
|
||||
}
|
||||
if err := a.objects.Delete(ctx, att.ObjectKey); err != nil {
|
||||
a.logger.Warn("compensating delete failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err))
|
||||
}
|
||||
}
|
||||
|
||||
// spoolBody пишет тело во временный файл и считает SHA-256 на лету. Файл удаляется из каталога сразу
|
||||
// после создания: данные живут, пока он открыт, поэтому при любом завершении, даже kill -9, на диске
|
||||
// ничего не остаётся и отдельная уборка не нужна. Это не хранилище: 202 вернётся только после S3 и PostgreSQL.
|
||||
func (a *Attachments) spoolBody(body io.Reader) (*os.File, int64, string, error) {
|
||||
file, err := os.CreateTemp("", "upload-*")
|
||||
if err != nil {
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
if err := os.Remove(file.Name()); err != nil {
|
||||
file.Close()
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
hash := sha256.New()
|
||||
source := &errorTrackingReader{r: body}
|
||||
// LimitReader на байт больше лимита: так отличается файл ровно на границе от файла больше неё.
|
||||
n, err := io.Copy(io.MultiWriter(file, hash), io.LimitReader(source, a.limits.MaxUploadBytes+1))
|
||||
switch {
|
||||
case source.err != nil:
|
||||
file.Close()
|
||||
// Клиент оборвал передачу или не уложился в таймаут. Отвечать чаще всего уже некому.
|
||||
return nil, 0, "", &validate.Error{Field: "body", Reason: "cannot read body"}
|
||||
case err != nil:
|
||||
file.Close()
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
case n > a.limits.MaxUploadBytes:
|
||||
file.Close()
|
||||
return nil, 0, "", domain.ErrPayloadTooLarge
|
||||
}
|
||||
return file, n, hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// errorTrackingReader отделяет ошибку чтения от клиента (400) от ошибки записи на диск (503).
|
||||
type errorTrackingReader struct {
|
||||
r io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *errorTrackingReader) Read(p []byte) (int, error) {
|
||||
n, err := e.r.Read(p)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
e.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func parseImageType(header string) (string, error) {
|
||||
mediaType, _, err := mime.ParseMediaType(header)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnsupportedMedia
|
||||
}
|
||||
switch mediaType {
|
||||
case domain.ContentTypePNG, domain.ContentTypeJPEG:
|
||||
return mediaType, nil
|
||||
}
|
||||
return "", domain.ErrUnsupportedMedia
|
||||
}
|
||||
|
||||
func (a *Attachments) Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) {
|
||||
id, err := validate.CanonicalUUID("attachment_id", attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return a.repo.AttachmentForMember(ctx, callerID, id)
|
||||
}
|
||||
|
||||
func (a *Attachments) Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error) {
|
||||
if err := validateVariantName(variant); err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
att, err := a.Get(ctx, callerID, attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if att.Status != domain.StatusReady {
|
||||
return domain.Attachment{}, nil, domain.ErrConflict
|
||||
}
|
||||
if variant != VariantOriginal {
|
||||
found := false
|
||||
for _, v := range att.Variants {
|
||||
if v.Name == variant {
|
||||
att.ObjectKey = "variants/" + att.ID + "/v1/" + variant
|
||||
att.ContentType, att.SizeBytes, att.SHA256 = v.ContentType, v.SizeBytes, v.SHA256
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return domain.Attachment{}, nil, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
body, size, err := a.objects.Get(ctx, att.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, objectstore.ErrNotFound) {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object missing in bucket", att.ID)
|
||||
}
|
||||
a.logger.Warn("attachment object get failed", slog.Any("err", err))
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if size != att.SizeBytes {
|
||||
body.Close()
|
||||
return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object size %d differs from metadata %d", att.ID, size, att.SizeBytes)
|
||||
}
|
||||
return att, body, nil
|
||||
}
|
||||
|
||||
func validateVariantName(variant string) error {
|
||||
switch variant {
|
||||
case VariantOriginal, "thumbnail", "crop", "optimized":
|
||||
return nil
|
||||
}
|
||||
return &validate.Error{Field: "variant", Reason: "unknown variant"}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token"
|
||||
)
|
||||
|
||||
var (
|
||||
_ AuthService = (*Auth)(nil)
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
users store.UserStore
|
||||
sessions session.Store
|
||||
hasher *password.Hasher
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func NewAuth(users store.UserStore, sessions session.Store, hasher *password.Hasher, ttl time.Duration) (*Auth, error) {
|
||||
dummy, err := hasher.Hash(context.Background(), "dummy-password-for-timing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: dummy hash: %w", err)
|
||||
}
|
||||
return &Auth{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
ttl: ttl,
|
||||
now: time.Now,
|
||||
dummyHash: dummy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Login(ctx context.Context, username, plainPassword string) (domain.Session, error) {
|
||||
user, hash, err := a.users.CredentialsByUsername(ctx, username)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
_, _ = a.hasher.Verify(ctx, plainPassword, a.dummyHash)
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
case err != nil:
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
ok, err := a.hasher.Verify(ctx, plainPassword, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, password.ErrMalformedHash) {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
return domain.Session{}, err
|
||||
}
|
||||
if !ok {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
|
||||
plain, tokenHash, err := token.New()
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
expiresAt := a.now().Add(a.ttl).UTC().Truncate(time.Second)
|
||||
if err := a.sessions.Save(ctx, tokenHash, session.Session{UserID: user.ID, ExpiresAt: expiresAt}); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{Token: plain, ExpiresAt: expiresAt, User: user}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Authenticate(ctx context.Context, plainToken string) (string, error) {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
s, err := a.sessions.Get(ctx, tokenHash)
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !a.now().Before(s.ExpiresAt) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
return s.UserID, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Logout(ctx context.Context, plainToken string) error {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return domain.ErrUnauthorized
|
||||
}
|
||||
return a.sessions.Delete(ctx, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ChatsService = (*Chats)(nil)
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
store store.ChatStore
|
||||
}
|
||||
|
||||
func NewChats(s store.ChatStore) *Chats {
|
||||
return &Chats{store: s}
|
||||
}
|
||||
|
||||
func (c *Chats) Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if err := validate.ChatTitle(title); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
memberIDs, err := validate.MemberIDs(memberIDs, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.CreateChat(ctx, callerID, title, memberIDs)
|
||||
}
|
||||
|
||||
func (c *Chats) Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.ChatByID(ctx, callerID, chatID)
|
||||
}
|
||||
|
||||
func (c *Chats) List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
return c.store.ListChats(ctx, callerID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
type signedMemory struct{ *objectstore.Memory }
|
||||
|
||||
func (s signedMemory) UploadMAC(b []byte) []byte {
|
||||
h := sha256.Sum256(append([]byte("test-key"), b...))
|
||||
return h[:]
|
||||
}
|
||||
func (s signedMemory) PresignUpload(_ context.Context, key, _ string, _ int64) (string, error) {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func TestDirectSizeExpiryAndCleanup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := store.New()
|
||||
alice, err := repo.CreateUser(ctx, "alice", "Alice", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := repo.CreateChat(ctx, alice.ID, "chat", []string{alice.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects := signedMemory{objectstore.NewMemory()}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
svc := NewAttachments(repo, objects, AttachmentLimits{MaxUploadBytes: 1024, MaxImagePixels: 100, MaxConcurrentUploads: 2}, logger)
|
||||
data := []byte("1234")
|
||||
sum := sha256.Sum256(data)
|
||||
u, err := svc.InitDirect(ctx, alice.ID, chat.ID, DirectInput{Filename: "x.png", ContentType: "image/png", SizeBytes: 4, SHA256: hex.EncodeToString(sum[:])})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects.PutAt(u.URL, data[:3], time.Now())
|
||||
if _, err = svc.CompleteDirect(ctx, alice.ID, chat.ID, u.Token); !errors.Is(err, domain.ErrInvalidArgument) {
|
||||
t.Fatalf("wrong size: %v", err)
|
||||
}
|
||||
// Expire a correctly authenticated ticket without sleeping in a unit test.
|
||||
encoded := bytes.Split([]byte(u.Token), []byte("."))[0]
|
||||
raw, _ := base64.RawURLEncoding.DecodeString(string(encoded))
|
||||
var ticket directTicket
|
||||
if err = json.Unmarshal(raw, &ticket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ticket.Expires = time.Now().Add(-time.Second).Unix()
|
||||
raw, _ = json.Marshal(ticket)
|
||||
token := base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(objects.UploadMAC(raw))
|
||||
if _, err = svc.CompleteDirect(ctx, alice.ID, chat.ID, token); !errors.Is(err, domain.ErrConflict) {
|
||||
t.Fatalf("expired: %v", err)
|
||||
}
|
||||
future := time.Now().Add(6 * time.Minute)
|
||||
report, err := janitor.Run(ctx, objects, noMetadata{}, janitor.Options{Prefix: ObjectKeyPrefix, Grace: 5 * time.Minute, MaxDeletes: 100, Now: func() time.Time { return future }, Logger: logger})
|
||||
if err != nil || report.Deleted != 1 {
|
||||
t.Fatalf("cleanup: %+v %v", report, err)
|
||||
}
|
||||
if _, _, err = objects.Get(ctx, u.URL); !errors.Is(err, objectstore.ErrNotFound) {
|
||||
t.Fatalf("abandoned staging remains: %v", err)
|
||||
}
|
||||
report, err = janitor.Run(ctx, objects, noMetadata{}, janitor.Options{Prefix: ObjectKeyPrefix, Grace: 5 * time.Minute, MaxDeletes: 100, Now: func() time.Time { return future }, Logger: logger})
|
||||
if err != nil || report.Deleted != 0 {
|
||||
t.Fatalf("repeat cleanup: %+v %v", report, err)
|
||||
}
|
||||
}
|
||||
|
||||
type noMetadata struct{}
|
||||
|
||||
func (noMetadata) ExistingObjectKeys(context.Context, []string) (map[string]struct{}, error) {
|
||||
return map[string]struct{}{}, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ MessagesService = (*Messages)(nil)
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
store store.MessageStore
|
||||
}
|
||||
|
||||
func NewMessages(s store.MessageStore) *Messages {
|
||||
return &Messages{store: s}
|
||||
}
|
||||
|
||||
func (m *Messages) Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.IdempotencyKey(idempotencyKey); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
ids, err := validate.AttachmentIDs(attachmentIDs)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.MessageText(text, len(ids) > 0); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
return m.store.AddMessage(ctx, callerID, chatID, idempotencyKey, text, ids)
|
||||
}
|
||||
|
||||
func (m *Messages) List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return m.store.ListMessages(ctx, callerID, chatID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type UsersService interface {
|
||||
Register(ctx context.Context, username, displayName, password string) (domain.User, error)
|
||||
Me(ctx context.Context, callerID string) (domain.User, error)
|
||||
}
|
||||
|
||||
type ChatsService interface {
|
||||
Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error)
|
||||
Get(ctx context.Context, callerID, chatID string) (domain.Chat, error)
|
||||
List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessagesService interface {
|
||||
Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error)
|
||||
List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// VariantOriginal — вариант содержимого по умолчанию.
|
||||
const VariantOriginal = "original"
|
||||
|
||||
// UploadInput — параметры загрузки файла. Body читается не дальше лимита размера.
|
||||
type UploadInput struct {
|
||||
CallerID string
|
||||
ChatID string
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type AttachmentsService interface {
|
||||
Upload(ctx context.Context, in UploadInput) (domain.Attachment, error)
|
||||
Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error)
|
||||
// Content возвращает метаданные и поток байтов. Поток обязательно закрыть.
|
||||
Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type AuthService interface {
|
||||
Login(ctx context.Context, username, password string) (domain.Session, error)
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
Logout(ctx context.Context, token string) error
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ UsersService = (*Users)(nil)
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
store store.UserStore
|
||||
hasher *password.Hasher
|
||||
}
|
||||
|
||||
func NewUsers(s store.UserStore, h *password.Hasher) *Users {
|
||||
return &Users{store: s, hasher: h}
|
||||
}
|
||||
|
||||
func (u *Users) Register(ctx context.Context, username, displayName, plainPassword string) (domain.User, error) {
|
||||
if err := validate.Username(username); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.DisplayName(displayName); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.Password(plainPassword); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
hash, err := u.hasher.Hash(ctx, plainPassword)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
return u.store.CreateUser(ctx, username, displayName, hash)
|
||||
}
|
||||
|
||||
func (u *Users) Me(ctx context.Context, callerID string) (domain.User, error) {
|
||||
return u.store.UserByID(ctx, callerID)
|
||||
}
|
||||
Reference in New Issue
Block a user