Выполнение lab4 на 4
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func createAttachment(w http.ResponseWriter, r *http.Request, attachments *service.Attachments, chatID string) {
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
if attachments == nil {
|
||||
writeAppError(w, store.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil || len(query["filename"]) != 1 {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second)
|
||||
defer cancel()
|
||||
a, err := attachments.Create(ctx, userFromContext(ctx).ID, chatID, query.Get("filename"), r.Header.Get("Content-Type"), r.Body, r.ContentLength)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, a)
|
||||
}
|
||||
|
||||
func attachmentRoutes(w http.ResponseWriter, r *http.Request, attachments *service.Attachments) {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
if attachments == nil {
|
||||
writeAppError(w, store.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/attachments/"), "/")
|
||||
if parts[0] == "" || len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") {
|
||||
writeAppError(w, store.ErrNotFound)
|
||||
return
|
||||
}
|
||||
a, err := attachments.Get(r.Context(), userFromContext(r.Context()).ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
if len(parts) == 1 {
|
||||
writeJSON(w, http.StatusOK, a)
|
||||
return
|
||||
}
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
if len(query["variant"]) > 1 {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
if variant := query.Get("variant"); variant != "" && variant != "original" {
|
||||
writeAppError(w, store.ErrNotFound)
|
||||
return
|
||||
}
|
||||
original, err := attachments.Open(r.Context(), a)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
defer original.Body.Close()
|
||||
w.Header().Set("Content-Type", a.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
if _, err := io.CopyBuffer(w, original.Body, make([]byte, 32*1024)); err != nil {
|
||||
log.Print("attachment download stream interrupted")
|
||||
// Headers may already be sent: abort rather than append a JSON error to bytes.
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ type createChatRequest struct {
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (api *API) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -340,7 +341,7 @@ func TestMessagePagination(t *testing.T) {
|
||||
}
|
||||
|
||||
for i := range sent {
|
||||
if got[i] != sent[i] {
|
||||
if !reflect.DeepEqual(got[i], sent[i]) {
|
||||
t.Fatalf("message %d differs or is out of order", i)
|
||||
}
|
||||
}
|
||||
@@ -490,7 +491,7 @@ func TestConcurrentMessages100From10Clients(t *testing.T) {
|
||||
seen[message.ID] = true
|
||||
|
||||
want, exists := expected[message.ID]
|
||||
if !exists || want != message {
|
||||
if !exists || !reflect.DeepEqual(want, message) {
|
||||
t.Fatalf("missing or changed message: %s", message.ID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/objectstore"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/upload"
|
||||
)
|
||||
|
||||
type errorResponse struct {
|
||||
@@ -21,6 +24,18 @@ type errorDetails struct {
|
||||
|
||||
func writeAppError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrAttachmentNotReady):
|
||||
writeError(w, http.StatusConflict, "conflict", "Attachment is not ready")
|
||||
case errors.Is(err, upload.ErrTooLarge):
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "Attachment limit exceeded")
|
||||
case errors.Is(err, upload.ErrMediaType):
|
||||
writeError(w, http.StatusUnsupportedMediaType, "unsupported_media_type", "Valid PNG or JPEG required")
|
||||
case errors.Is(err, upload.ErrFilename), errors.Is(err, upload.ErrInterrupted):
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Invalid attachment request")
|
||||
case errors.Is(err, objectstore.ErrNotFound):
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
case errors.Is(err, objectstore.ErrUnavailable), errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled):
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Service temporarily unavailable")
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
writeError(w, http.StatusConflict, "conflict", "Idempotency key already used for another message")
|
||||
|
||||
|
||||
@@ -19,6 +19,10 @@ func readJSON(
|
||||
dst any,
|
||||
requiredFields ...string,
|
||||
) bool {
|
||||
return readJSONFields(w, r, dst, requiredFields, nil)
|
||||
}
|
||||
|
||||
func readJSONFields(w http.ResponseWriter, r *http.Request, dst any, requiredFields, optionalFields []string) bool {
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
writeError(
|
||||
@@ -67,8 +71,8 @@ func readJSON(
|
||||
return invalid()
|
||||
}
|
||||
|
||||
for name := range fields {
|
||||
if !slices.Contains(requiredFields, name) {
|
||||
for name, value := range fields {
|
||||
if (!slices.Contains(requiredFields, name) && !slices.Contains(optionalFields, name)) || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,19 +10,22 @@ import (
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (http.Handler, error) {
|
||||
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64, attachmentServices ...*service.Attachments) (http.Handler, error) {
|
||||
registration := service.NewRegistration(db)
|
||||
sessions, err := service.NewSessions(db, registration, ttl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats := &persistentAPI{messenger: service.NewPersistentMessenger(db)}
|
||||
if len(attachmentServices) > 0 {
|
||||
chats.attachments = attachmentServices[0]
|
||||
}
|
||||
return withInstanceID(withRequestID(withAccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if stopping.Load() && r.URL.Path != "/health/live" {
|
||||
writeAppError(w, store.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
|
||||
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") || strings.HasPrefix(r.URL.Path, "/api/v1/attachments/") {
|
||||
token, err := bearerToken(r)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
@@ -34,6 +37,10 @@ func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int6
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userContextKey{}, user)
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/attachments/") {
|
||||
attachmentRoutes(w, r.WithContext(ctx), chats.attachments)
|
||||
return
|
||||
}
|
||||
chats.chatRoutes(w, r.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
@@ -54,6 +61,12 @@ func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int6
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
if chats.attachments != nil {
|
||||
if err := chats.attachments.Ready(r.Context()); err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
handleHealth(w, r)
|
||||
case "/api/v1/users":
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
|
||||
@@ -8,7 +8,10 @@ import (
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type persistentAPI struct{ messenger *service.PersistentMessenger }
|
||||
type persistentAPI struct {
|
||||
messenger *service.PersistentMessenger
|
||||
attachments *service.Attachments
|
||||
}
|
||||
|
||||
func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
actor := userFromContext(r.Context())
|
||||
@@ -53,6 +56,10 @@ func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||
parts := strings.Split(path, "/")
|
||||
if len(parts) == 2 && parts[0] != "" && parts[1] == "attachments" {
|
||||
createAttachment(w, r, api.attachments, parts[0])
|
||||
return
|
||||
}
|
||||
|
||||
if len(parts) == 1 && parts[0] != "" {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
@@ -83,12 +90,12 @@ func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createMessageRequest
|
||||
if !readJSON(w, r, &body, "text") {
|
||||
if !readJSONFields(w, r, &body, []string{"text"}, []string{"attachment_ids"}) {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := api.messenger.CreateMessage(r.Context(),
|
||||
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"),
|
||||
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"), body.AttachmentIDs...,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []Variant `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
@@ -17,9 +17,10 @@ type Chat struct {
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// Package objectstore stores original bytes; chat authorization belongs to the service.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v7/pkg/s3utils"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConfig = errors.New("invalid S3 configuration")
|
||||
ErrInput = errors.New("invalid object input")
|
||||
ErrNotFound = errors.New("S3 object not found")
|
||||
ErrUnavailable = errors.New("S3 unavailable")
|
||||
)
|
||||
|
||||
const operationTimeout = 30 * time.Second
|
||||
|
||||
type Config struct {
|
||||
Endpoint, Region, Bucket string
|
||||
AccessKeyFile, SecretKeyFile string
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
core *minio.Core
|
||||
bucket string
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
func New(config Config) (*S3, error) {
|
||||
u, err := url.Parse(config.Endpoint)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" || config.Region == "" {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
if err := s3utils.CheckValidBucketNameStrict(config.Bucket); err != nil {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
access, err := readSecret(config.AccessKeyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
secret, err := readSecret(config.SecretKeyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
||||
TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 5 * time.Second,
|
||||
IdleConnTimeout: 60 * time.Second, MaxIdleConns: 10, MaxIdleConnsPerHost: 10,
|
||||
}
|
||||
core, err := minio.NewCore(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https",
|
||||
Region: config.Region, BucketLookup: minio.BucketLookupPath,
|
||||
Transport: transport, MaxRetries: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
return &S3{core: core, bucket: config.Bucket, transport: transport}, nil
|
||||
}
|
||||
|
||||
func readSecret(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", ErrConfig
|
||||
}
|
||||
value := strings.TrimRight(string(data), "\r\n")
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return "", ErrConfig
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *S3) Close() { s.transport.CloseIdleConnections() }
|
||||
|
||||
func (s *S3) Check(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond)
|
||||
defer cancel()
|
||||
exists, err := s.core.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return storageError(ctx, err)
|
||||
}
|
||||
if !exists {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ObjectKey(id string) (string, error) {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil || parsed.String() != id {
|
||||
return "", ErrInput
|
||||
}
|
||||
return "attachments/" + id, nil
|
||||
}
|
||||
|
||||
func (s *S3) Put(ctx context.Context, id string, source io.Reader, size int64, contentType, sha256 string) error {
|
||||
key, err := ObjectKey(id)
|
||||
checksum, checksumErr := hex.DecodeString(sha256)
|
||||
if err != nil || source == nil || size < 1 || size > 10485760 || (contentType != "image/png" && contentType != "image/jpeg") || checksumErr != nil || len(checksum) != 32 || strings.ToLower(sha256) != sha256 {
|
||||
return ErrInput
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
|
||||
defer cancel()
|
||||
_, err = s.core.PutObject(ctx, s.bucket, key, source, size, "", sha256, minio.PutObjectOptions{ContentType: contentType})
|
||||
return storageError(ctx, err)
|
||||
}
|
||||
|
||||
type Original struct {
|
||||
Body io.ReadCloser
|
||||
SizeBytes int64
|
||||
ContentType string
|
||||
}
|
||||
|
||||
func (s *S3) Open(ctx context.Context, id string) (Original, error) {
|
||||
key, err := ObjectKey(id)
|
||||
if err != nil {
|
||||
return Original{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
|
||||
body, info, _, err := s.core.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
mapped := storageError(ctx, err)
|
||||
cancel()
|
||||
return Original{}, mapped
|
||||
}
|
||||
return Original{Body: &originalBody{ReadCloser: body, cancel: cancel}, SizeBytes: info.Size, ContentType: info.ContentType}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, id string) error {
|
||||
key, err := ObjectKey(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
|
||||
defer cancel()
|
||||
return storageError(ctx, s.core.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}))
|
||||
}
|
||||
|
||||
func storageError(ctx context.Context, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "NoSuchKey", "NoSuchObject":
|
||||
return ErrNotFound
|
||||
default:
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
type originalBody struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
once sync.Once
|
||||
err error
|
||||
}
|
||||
|
||||
func (b *originalBody) Close() error {
|
||||
b.once.Do(func() { b.err = b.ReadCloser.Close(); b.cancel() })
|
||||
return b.err
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/upload"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestObjectKey(t *testing.T) {
|
||||
for _, bad := range []string{"", "../x", "photo.png", "550E8400-E29B-41D4-A716-446655440000"} {
|
||||
if _, err := ObjectKey(bad); !errors.Is(err, ErrInput) {
|
||||
t.Fatalf("accepted key %q", bad)
|
||||
}
|
||||
}
|
||||
id := uuid.NewString()
|
||||
if key, err := ObjectKey(id); err != nil || key != "attachments/"+id {
|
||||
t.Fatal("invalid generated key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidConfig(t *testing.T) {
|
||||
for _, endpoint := range []string{"", "ftp://s3:9000", "http://user:password@s3:9000", "http://s3:9000/path", "http://s3:9000?secret=hidden"} {
|
||||
_, err := New(Config{Endpoint: endpoint, Region: "us-east-1", Bucket: "messenger-attachments"})
|
||||
if !errors.Is(err, ErrConfig) {
|
||||
t.Fatal("invalid config accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3Integration(t *testing.T) {
|
||||
if os.Getenv("S3_INTEGRATION") != "1" {
|
||||
t.Skip("explicit S3 integration mode required")
|
||||
}
|
||||
config := Config{
|
||||
Endpoint: os.Getenv("S3_ENDPOINT"), Region: os.Getenv("S3_REGION"), Bucket: os.Getenv("S3_BUCKET"),
|
||||
AccessKeyFile: os.Getenv("S3_ACCESS_KEY_ID_FILE"), SecretKeyFile: os.Getenv("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
}
|
||||
client, err := New(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
id := uuid.NewString()
|
||||
defer func() {
|
||||
if err := client.Delete(context.Background(), id); err != nil {
|
||||
t.Errorf("fixture cleanup: %v", err)
|
||||
}
|
||||
}()
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 3, 2))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := upload.NewValidator(t.TempDir()).Prepare(ctx, bytes.NewReader(encoded.Bytes()), "image/png", "original.png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if err := client.Put(ctx, id, p.File, p.SizeBytes, p.ContentType, p.SHA256); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log("PASS: validated original uploaded with API credentials")
|
||||
original, err := client.Open(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, readErr := io.ReadAll(original.Body)
|
||||
closeErr := original.Body.Close()
|
||||
if readErr != nil || closeErr != nil {
|
||||
t.Fatalf("download: %v %v", readErr, closeErr)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
if !bytes.Equal(data, encoded.Bytes()) || original.SizeBytes != p.SizeBytes || original.ContentType != "image/png" || hex.EncodeToString(sum[:]) != p.SHA256 {
|
||||
t.Fatal("original or metadata mismatch")
|
||||
}
|
||||
t.Log("PASS: downloaded original bytes, MIME, size and SHA-256 match")
|
||||
if err := client.Delete(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Open(ctx, id); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("missing object: %v", err)
|
||||
}
|
||||
if err := client.Delete(ctx, id); err != nil {
|
||||
t.Fatal("repeat delete failed")
|
||||
}
|
||||
t.Log("PASS: deleted object is not found; repeat delete succeeds")
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err := client.Open(cancelled, id); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation: %v", err)
|
||||
}
|
||||
t.Log("PASS: caller cancellation propagated")
|
||||
badSecret := filepath.Join(t.TempDir(), "secret")
|
||||
if err := os.WriteFile(badSecret, []byte("deliberately-invalid-secret"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wrongConfig := config
|
||||
wrongConfig.SecretKeyFile = badSecret
|
||||
wrongClient, err := New(wrongConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer wrongClient.Close()
|
||||
if _, err := wrongClient.Open(ctx, id); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("credential failure: %v", err)
|
||||
}
|
||||
t.Log("PASS: incorrect credentials yield sanitized unavailable error")
|
||||
unavailableConfig := config
|
||||
unavailableConfig.Endpoint = "http://127.0.0.1:1"
|
||||
unavailableClient, err := New(unavailableConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer unavailableClient.Close()
|
||||
if _, err := unavailableClient.Open(ctx, id); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("unreachable endpoint: %v", err)
|
||||
}
|
||||
t.Log("PASS: unreachable endpoint yields sanitized unavailable error")
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/objectstore"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/upload"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Attachments struct {
|
||||
db *store.PostgresStore
|
||||
objects *objectstore.S3
|
||||
validator *upload.Validator
|
||||
}
|
||||
|
||||
func NewAttachments(db *store.PostgresStore, objects *objectstore.S3) *Attachments {
|
||||
return &Attachments{db: db, objects: objects, validator: upload.NewValidator("")}
|
||||
}
|
||||
|
||||
func (s *Attachments) Ready(ctx context.Context) error { return s.objects.Check(ctx) }
|
||||
|
||||
func (s *Attachments) Create(ctx context.Context, actor, chatID, filename, mime string, body io.Reader, length int64) (model.Attachment, error) {
|
||||
if !uuidPattern.MatchString(chatID) {
|
||||
return model.Attachment{}, ErrInvalidRequest
|
||||
}
|
||||
chatID = strings.ToLower(chatID)
|
||||
if _, err := s.db.GetChat(ctx, actor, chatID); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if length > upload.MaxBytes {
|
||||
return model.Attachment{}, upload.ErrTooLarge
|
||||
}
|
||||
p, err := s.validator.Prepare(ctx, body, mime, filename)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
defer func() {
|
||||
if err := p.Close(); err != nil {
|
||||
log.Print("attachment staging cleanup failed")
|
||||
}
|
||||
}()
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return model.Attachment{}, store.ErrUnavailable
|
||||
}
|
||||
a := model.Attachment{ID: id.String(), ChatID: chatID, OwnerID: actor, Filename: filename,
|
||||
ContentType: p.ContentType, SizeBytes: p.SizeBytes, SHA256: p.SHA256, Status: "ready", Variants: []model.Variant{}}
|
||||
if err := s.db.BeginUpload(ctx, a.ID, chatID, actor); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if err := s.objects.Put(ctx, a.ID, p.File, p.SizeBytes, p.ContentType, p.SHA256); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
key, _ := objectstore.ObjectKey(a.ID)
|
||||
// Publication and intent removal commit together; failed/unknown outcomes
|
||||
// are resolved by cleanup under the same DB row lock after the grace period.
|
||||
return s.db.SaveAttachment(ctx, a, key)
|
||||
}
|
||||
|
||||
type CleanupSummary struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
Candidates int `json:"candidates"`
|
||||
Deleted int `json:"deleted"`
|
||||
Protected int `json:"protected"`
|
||||
WouldDelete int `json:"would_delete"`
|
||||
Skipped int `json:"skipped"`
|
||||
Errors int `json:"errors"`
|
||||
}
|
||||
|
||||
func (s *Attachments) Cleanup(ctx context.Context, dryRun bool) (CleanupSummary, error) {
|
||||
result := CleanupSummary{DryRun: dryRun}
|
||||
ids, err := s.db.CleanupCandidates(ctx)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Candidates = len(ids)
|
||||
for _, id := range ids {
|
||||
action, err := s.db.CleanupUpload(ctx, id, dryRun, s.objects.Delete)
|
||||
if err != nil {
|
||||
result.Errors++
|
||||
continue
|
||||
}
|
||||
switch action {
|
||||
case "deleted":
|
||||
result.Deleted++
|
||||
case "protected":
|
||||
result.Protected++
|
||||
case "would_delete":
|
||||
result.WouldDelete++
|
||||
case "skipped":
|
||||
result.Skipped++
|
||||
}
|
||||
}
|
||||
if result.Errors > 0 {
|
||||
return result, store.ErrUnavailable
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Attachments) Get(ctx context.Context, actor, id string) (model.Attachment, error) {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Attachment{}, ErrInvalidRequest
|
||||
}
|
||||
return s.db.GetAttachment(ctx, actor, strings.ToLower(id))
|
||||
}
|
||||
|
||||
func (s *Attachments) Open(ctx context.Context, a model.Attachment) (objectstore.Original, error) {
|
||||
original, err := s.objects.Open(ctx, a.ID)
|
||||
if err != nil {
|
||||
return objectstore.Original{}, err
|
||||
}
|
||||
if original.SizeBytes != a.SizeBytes || original.ContentType != a.ContentType {
|
||||
original.Body.Close()
|
||||
return objectstore.Original{}, store.ErrUnavailable
|
||||
}
|
||||
return original, nil
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type PersistentMessenger struct{ db *store.PostgresStore }
|
||||
@@ -96,11 +97,24 @@ func (m *PersistentMessenger) ListChats(ctx context.Context, actor string, limit
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (m *PersistentMessenger) CreateMessage(ctx context.Context, actor, chatID, text, key string) (model.Message, error) {
|
||||
if !uuidPattern.MatchString(chatID) || !validText(text, 4000) || !idempotencyKeyPattern.MatchString(key) {
|
||||
func (m *PersistentMessenger) CreateMessage(ctx context.Context, actor, chatID, text, key string, attachmentIDs ...string) (model.Message, error) {
|
||||
if !uuidPattern.MatchString(chatID) || !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 || (strings.TrimSpace(text) == "" && len(attachmentIDs) == 0) || len(attachmentIDs) > 10 || !idempotencyKeyPattern.MatchString(key) {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
return m.db.CreateMessage(ctx, actor, strings.ToLower(chatID), text, key)
|
||||
normalized := make([]string, len(attachmentIDs))
|
||||
seen := make(map[string]bool, len(attachmentIDs))
|
||||
for i, id := range attachmentIDs {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
id = strings.ToLower(id)
|
||||
if seen[id] {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
seen[id] = true
|
||||
normalized[i] = id
|
||||
}
|
||||
return m.db.CreateMessage(ctx, actor, strings.ToLower(chatID), text, key, normalized...)
|
||||
}
|
||||
func (m *PersistentMessenger) ListMessages(ctx context.Context, actor, chatID string, limit int, cursor string) (Page[model.Message], error) {
|
||||
chat, err := m.GetChat(ctx, actor, chatID)
|
||||
|
||||
@@ -141,11 +141,12 @@ func (s *MemoryStore) CreateMessage(
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: actorID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
AttachmentIDs: []string{},
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: actorID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChat[chatID] = append(history, message)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgresStore) SaveAttachment(ctx context.Context, a model.Attachment, objectKey string) (model.Attachment, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Attachment{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var id string
|
||||
err = tx.QueryRow(ctx, `SELECT id::text FROM upload_intents WHERE id=$1 AND state='pending' AND expires_at>clock_timestamp() FOR UPDATE`, a.ID).Scan(&id)
|
||||
if err != nil {
|
||||
return model.Attachment{}, ErrUnavailable
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING created_at,updated_at`,
|
||||
a.ID, a.ChatID, a.OwnerID, objectKey, a.Filename, a.ContentType, a.SizeBytes, a.SHA256).Scan(&a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return model.Attachment{}, ErrUnavailable
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM upload_intents WHERE id=$1`, a.ID); err != nil {
|
||||
return model.Attachment{}, ErrUnavailable
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Attachment{}, ErrUnavailable
|
||||
}
|
||||
a.CreatedAt, a.UpdatedAt = a.CreatedAt.UTC(), a.UpdatedAt.UTC()
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetAttachment(ctx context.Context, actor, id string) (model.Attachment, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
a := model.Attachment{Variants: []model.Variant{}}
|
||||
err := s.pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.content_type,a.size_bytes,a.sha256,a.status,a.created_at,a.updated_at
|
||||
FROM attachments a WHERE a.id=$1 AND EXISTS(SELECT 1 FROM chat_members m WHERE m.chat_id=a.chat_id AND m.user_id=$2)`, id, actor).
|
||||
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, ErrUnavailable
|
||||
}
|
||||
a.CreatedAt, a.UpdatedAt = a.CreatedAt.UTC(), a.UpdatedAt.UTC()
|
||||
return a, nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package store
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
@@ -97,8 +98,12 @@ func (s *PostgresStore) ChatPage(ctx context.Context, actor string, limit int, a
|
||||
}
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key already used for another message")
|
||||
var ErrAttachmentNotReady = errors.New("attachment is not ready")
|
||||
|
||||
func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text, key string) (model.Message, error) {
|
||||
const messageColumns = `m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id::text FROM message_attachments ma WHERE ma.message_id=m.id ORDER BY ma.position)`
|
||||
|
||||
func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text, key string, attachmentIDs ...string) (model.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
id, err := newUUID()
|
||||
@@ -121,12 +126,12 @@ func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text,
|
||||
}
|
||||
var message model.Message
|
||||
|
||||
err = tx.QueryRow(ctx, `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at
|
||||
err = tx.QueryRow(ctx, `SELECT `+messageColumns+`
|
||||
FROM message_keys k JOIN messages m ON m.id=k.message_id
|
||||
WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3 AND k.expires_at>clock_timestamp()`,
|
||||
actor, chatID, key).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
|
||||
actor, chatID, key).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs)
|
||||
if err == nil {
|
||||
if message.Text != text {
|
||||
if message.Text != text || !slices.Equal(message.AttachmentIDs, attachmentIDs) {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
message.CreatedAt = message.CreatedAt.UTC()
|
||||
@@ -135,6 +140,19 @@ func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text,
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
for _, attachmentID := range attachmentIDs {
|
||||
var status string
|
||||
err := tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE`, attachmentID, chatID).Scan(&status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
if status != "ready" {
|
||||
return model.Message{}, ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
VALUES($1,$2,$3,$4,GREATEST(clock_timestamp(),
|
||||
COALESCE((SELECT created_at + INTERVAL '1 microsecond' FROM messages WHERE chat_id=$2 ORDER BY created_at DESC,id DESC LIMIT 1),clock_timestamp())))
|
||||
@@ -142,6 +160,14 @@ func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text,
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
message.AttachmentIDs = make([]string, len(attachmentIDs))
|
||||
copy(message.AttachmentIDs, attachmentIDs)
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO message_attachments(message_id,attachment_id,chat_id,position) VALUES($1,$2,$3,$4)`, message.ID, attachmentID, chatID, position)
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO message_keys(user_id,chat_id,key,message_id,expires_at)
|
||||
VALUES($1,$2,$3,$4,clock_timestamp()+INTERVAL '24 hours')
|
||||
ON CONFLICT(user_id,chat_id,key) DO UPDATE
|
||||
@@ -159,13 +185,13 @@ func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text,
|
||||
func (s *PostgresStore) MessagePage(ctx context.Context, chatID string, limit int, after *Position) ([]model.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1`
|
||||
query := `SELECT ` + messageColumns + ` FROM messages m WHERE m.chat_id=$1`
|
||||
args := []any{chatID, limit}
|
||||
if after != nil {
|
||||
query += ` AND (created_at,id)>($3,$4::uuid)`
|
||||
query += ` AND (m.created_at,m.id)>($3,$4::uuid)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY messages.created_at,messages.id LIMIT $2`
|
||||
query += ` ORDER BY m.created_at,m.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
@@ -174,7 +200,7 @@ func (s *PostgresStore) MessagePage(ctx context.Context, chatID string, limit in
|
||||
items := make([]model.Message, 0)
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgresStore) BeginUpload(ctx context.Context, id, chatID, ownerID string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if _, err := s.pool.Exec(ctx, `INSERT INTO upload_intents(id,chat_id,owner_id) VALUES($1,$2,$3)`, id, chatID, ownerID); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanupCandidates is bounded. Each candidate is locked and rechecked later.
|
||||
func (s *PostgresStore) CleanupCandidates(ctx context.Context) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `SELECT id::text FROM upload_intents
|
||||
WHERE expires_at<=clock_timestamp() AND next_cleanup_at<=clock_timestamp()
|
||||
ORDER BY next_cleanup_at,id LIMIT 100`)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// CleanupUpload serializes with publication using the same intent row lock.
|
||||
// No deletion is attempted if the DB is unavailable or a row is still fresh.
|
||||
func (s *PostgresStore) CleanupUpload(ctx context.Context, id string, dryRun bool, remove func(context.Context, string) error) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var locked string
|
||||
err = tx.QueryRow(ctx, `SELECT id::text FROM upload_intents
|
||||
WHERE id=$1 AND expires_at<=clock_timestamp() AND next_cleanup_at<=clock_timestamp()
|
||||
FOR UPDATE SKIP LOCKED`, id).Scan(&locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "skipped", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
var published bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE id=$1)`, id).Scan(&published); err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
if published {
|
||||
if dryRun {
|
||||
return "protected", nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM upload_intents WHERE id=$1`, id); err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
return "protected", nil
|
||||
}
|
||||
if dryRun {
|
||||
return "would_delete", nil
|
||||
}
|
||||
if err := remove(ctx, id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Retain a tombstone: repeat deletion catches a late PUT after a crashed API.
|
||||
if _, err := tx.Exec(ctx, `UPDATE upload_intents SET state='abandoned',next_cleanup_at=clock_timestamp()+INTERVAL '10 minutes' WHERE id=$1`, id); err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
return "deleted", nil
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mime"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxBytes int64 = 10 * 1024 * 1024
|
||||
MaxPixels = 40_000_000
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFilename = errors.New("invalid attachment filename")
|
||||
ErrMediaType = errors.New("unsupported or corrupt image")
|
||||
ErrTooLarge = errors.New("attachment limit exceeded")
|
||||
ErrInterrupted = errors.New("upload interrupted")
|
||||
)
|
||||
|
||||
type Validator struct {
|
||||
tempDir string
|
||||
slot chan struct{}
|
||||
}
|
||||
|
||||
func NewValidator(tempDir string) *Validator {
|
||||
return &Validator{tempDir: tempDir, slot: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
type Prepared struct {
|
||||
File *os.File
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
ContentType string
|
||||
Width int
|
||||
Height int
|
||||
release func()
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (p *Prepared) Close() error {
|
||||
p.closeOnce.Do(func() {
|
||||
p.closeErr = errors.Join(p.File.Close(), os.Remove(p.File.Name()))
|
||||
p.release()
|
||||
})
|
||||
return p.closeErr
|
||||
}
|
||||
|
||||
func ValidFilename(name string) bool {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range name {
|
||||
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (v *Validator) Prepare(ctx context.Context, source io.Reader, contentType, filename string) (_ *Prepared, err error) {
|
||||
if !ValidFilename(filename) {
|
||||
return nil, ErrFilename
|
||||
}
|
||||
mediaType, _, parseErr := mime.ParseMediaType(contentType)
|
||||
if parseErr != nil || (mediaType != "image/png" && mediaType != "image/jpeg") {
|
||||
return nil, ErrMediaType
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case v.slot <- struct{}{}:
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
<-v.slot
|
||||
}
|
||||
}()
|
||||
file, err := os.CreateTemp(v.tempDir, "attachment-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create upload staging: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
file.Close()
|
||||
os.Remove(file.Name())
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(contextReader{ctx, source}, MaxBytes+1), make([]byte, 32*1024))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stage upload: %w", err)
|
||||
}
|
||||
if size > MaxBytes {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config, format, err := image.DecodeConfig(file)
|
||||
if err != nil || "image/"+format != mediaType {
|
||||
return nil, ErrMediaType
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 || config.Width > MaxPixels/config.Height {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, _, err := image.Decode(contextReader{ctx, file}); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, ErrMediaType
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Prepared{
|
||||
File: file, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)),
|
||||
ContentType: mediaType, Width: config.Width, Height: config.Height,
|
||||
release: func() { <-v.slot },
|
||||
}, nil
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
src io.Reader
|
||||
}
|
||||
|
||||
func (r contextReader) Read(p []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, err := r.src.Read(p)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return n, fmt.Errorf("%w: %w", ErrInterrupted, err)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fixture(t *testing.T, format string) []byte {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 3, 2))
|
||||
var err error
|
||||
if format == "png" {
|
||||
err = png.Encode(&data, img)
|
||||
} else {
|
||||
err = jpeg.Encode(&data, img, nil)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data.Bytes()
|
||||
}
|
||||
|
||||
func TestOriginalPreserved(t *testing.T) {
|
||||
for _, format := range []string{"png", "jpeg"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
data := fixture(t, format)
|
||||
p, err := NewValidator(t.TempDir()).Prepare(context.Background(), bytes.NewReader(data), "image/"+format, "фото."+format)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
original, err := io.ReadAll(p.File)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := sha256.Sum256(data)
|
||||
if !bytes.Equal(original, data) || p.SizeBytes != int64(len(data)) || p.SHA256 != hex.EncodeToString(hash[:]) || p.Width != 3 || p.Height != 2 {
|
||||
t.Fatal("original bytes or metadata changed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidFilesAndCleanup(t *testing.T) {
|
||||
valid := fixture(t, "png")
|
||||
// A valid IHDR advertises excessive dimensions, with a corrected CRC.
|
||||
huge := bytes.Clone(valid)
|
||||
binary.BigEndian.PutUint32(huge[16:20], 40001)
|
||||
binary.BigEndian.PutUint32(huge[20:24], 1000)
|
||||
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
|
||||
for _, tc := range []struct {
|
||||
name, mime string
|
||||
data []byte
|
||||
want error
|
||||
}{
|
||||
{"empty", "image/png", nil, ErrMediaType},
|
||||
{"text", "image/png", []byte("not an image"), ErrMediaType},
|
||||
{"spoofed MIME", "image/jpeg", valid, ErrMediaType},
|
||||
{"unsupported MIME", "text/plain", valid, ErrMediaType},
|
||||
{"truncated after header", "image/png", valid[:33], ErrMediaType},
|
||||
{"pixel limit before decode", "image/png", huge, ErrTooLarge},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
_, err := NewValidator(dir).Prepare(context.Background(), bytes.NewReader(tc.data), tc.mime, "photo.png")
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("got %v; want %v", err, tc.want)
|
||||
}
|
||||
files, err := os.ReadDir(dir)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("staging not cleaned: %v %v", files, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type countingStream struct{ read int64 }
|
||||
|
||||
func (s *countingStream) Read(p []byte) (int, error) {
|
||||
clear(p)
|
||||
s.read += int64(len(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestByteLimitStopsInfiniteStream(t *testing.T) {
|
||||
stream := &countingStream{}
|
||||
dir := t.TempDir()
|
||||
_, err := NewValidator(dir).Prepare(context.Background(), stream, "image/png", "photo.png")
|
||||
if !errors.Is(err, ErrTooLarge) || stream.read != MaxBytes+1 {
|
||||
t.Fatalf("got %v after reading %d bytes", err, stream.read)
|
||||
}
|
||||
files, _ := os.ReadDir(dir)
|
||||
if len(files) != 0 {
|
||||
t.Fatal("oversized staging file remains")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilename(t *testing.T) {
|
||||
for _, name := range []string{"", " ", "../x.png", `a\b.png`, "x\x00.png", "x\n.png", string([]byte{0xff}), strings.Repeat("я", 256)} {
|
||||
if ValidFilename(name) {
|
||||
t.Errorf("accepted filename %q", name)
|
||||
}
|
||||
}
|
||||
if !ValidFilename(strings.Repeat("я", 255)) {
|
||||
t.Fatal("Unicode length counted as bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancellationAndReadFailure(t *testing.T) {
|
||||
v := NewValidator(t.TempDir())
|
||||
v.slot <- struct{}{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := v.Prepare(ctx, bytes.NewReader(nil), "image/png", "x.png"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancelled admission: %v", err)
|
||||
}
|
||||
<-v.slot
|
||||
if _, err := v.Prepare(context.Background(), brokenReader{}, "image/png", "x.png"); !errors.Is(err, ErrInterrupted) {
|
||||
t.Fatalf("interrupted upload: %v", err)
|
||||
}
|
||||
files, _ := os.ReadDir(v.tempDir)
|
||||
if len(files) != 0 {
|
||||
t.Fatal("interrupted staging file remains")
|
||||
}
|
||||
}
|
||||
|
||||
type brokenReader struct{}
|
||||
|
||||
func (brokenReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
|
||||
Reference in New Issue
Block a user