forked from mtusi2026/mtusi2026lab4
feat: lab4 - S3 attachments, image validation, failover
This commit is contained in:
+253
-9
@@ -1,23 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
"github.com/minio/minio-go/v7"
|
||||
|
||||
"mtusi2026lab3/internal/config"
|
||||
"mtusi2026lab3/internal/ident"
|
||||
"mtusi2026lab3/internal/password"
|
||||
"mtusi2026lab3/internal/s3"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -28,11 +41,15 @@ const (
|
||||
instanceHeader = "X-Instance-Id"
|
||||
idempotencyHeader = "Idempotency-Key"
|
||||
maxIdempotencyKey = 128
|
||||
maxUploadSize = 10 * 1024 * 1024
|
||||
maxPixels = 40000000
|
||||
)
|
||||
|
||||
type server struct {
|
||||
db *sql.DB
|
||||
instance string
|
||||
s3Client *minio.Client
|
||||
s3Bucket string
|
||||
}
|
||||
|
||||
type credentials struct {
|
||||
@@ -41,16 +58,18 @@ type credentials struct {
|
||||
}
|
||||
|
||||
type newMessage struct {
|
||||
Recipient string `json:"recipient"`
|
||||
Body string `json:"body"`
|
||||
Recipient string `json:"recipient"`
|
||||
Body string `json:"body"`
|
||||
AttachmentIDs []int64 `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type message struct {
|
||||
ID int64 `json:"id"`
|
||||
SenderID int64 `json:"sender_id"`
|
||||
Recipient string `json:"recipient"`
|
||||
Body string `json:"body"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID int64 `json:"id"`
|
||||
SenderID int64 `json:"sender_id"`
|
||||
Recipient string `json:"recipient"`
|
||||
Body string `json:"body"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
AttachmentIDs []int64 `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type session struct {
|
||||
@@ -76,7 +95,17 @@ func main() {
|
||||
log.Fatalf("ping database: %v", err)
|
||||
}
|
||||
|
||||
srv := &server{db: db, instance: cfg.InstanceID}
|
||||
s3Client, s3Bucket, err := s3.NewClient()
|
||||
if err != nil {
|
||||
log.Fatalf("s3 client: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
if err := s3.EnsureBucket(ctx, s3Client, s3Bucket); err != nil {
|
||||
log.Fatalf("ensure bucket: %v", err)
|
||||
}
|
||||
|
||||
srv := &server{db: db, instance: cfg.InstanceID, s3Client: s3Client, s3Bucket: s3Bucket}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + cfg.Port,
|
||||
@@ -111,6 +140,8 @@ func (s *server) routes() http.Handler {
|
||||
mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
|
||||
mux.HandleFunc("GET /api/messages", s.handleListMessages)
|
||||
mux.HandleFunc("POST /api/messages", s.handleCreateMessage)
|
||||
mux.HandleFunc("POST /api/attachments", s.handleUploadAttachment)
|
||||
mux.HandleFunc("GET /api/attachments/", s.handleDownloadAttachment)
|
||||
return s.addInstanceID(mux)
|
||||
}
|
||||
|
||||
@@ -212,6 +243,7 @@ func (s *server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "scan failed")
|
||||
return
|
||||
}
|
||||
m.AttachmentIDs = s.getAttachmentIDs(r.Context(), m.ID)
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
@@ -222,6 +254,24 @@ func (s *server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, items)
|
||||
}
|
||||
|
||||
func (s *server) getAttachmentIDs(ctx context.Context, messageID int64) []int64 {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT id FROM attachments WHERE message_id = $1 ORDER BY id`, messageID)
|
||||
if err != nil {
|
||||
return []int64{}
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ids := make([]int64, 0)
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err == nil {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func (s *server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
sess, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
@@ -282,6 +332,20 @@ func (s *server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
for _, attID := range in.AttachmentIDs {
|
||||
_, err := tx.ExecContext(ctx,
|
||||
`UPDATE attachments SET message_id = $1 WHERE id = $2 AND message_id IS NULL`,
|
||||
msg.ID, attID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "attachment link failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
msg.AttachmentIDs = in.AttachmentIDs
|
||||
if msg.AttachmentIDs == nil {
|
||||
msg.AttachmentIDs = []int64{}
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "response encode failed")
|
||||
@@ -290,7 +354,6 @@ func (s *server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO idempotency_keys (key, response) VALUES ($1, $2::jsonb)`, key, payload); err != nil {
|
||||
// A concurrent request on another replica won the race for this key.
|
||||
tx.Rollback()
|
||||
var existing []byte
|
||||
if readErr := s.db.QueryRowContext(ctx,
|
||||
@@ -310,6 +373,187 @@ func (s *server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeRawJSON(w, http.StatusCreated, payload)
|
||||
}
|
||||
|
||||
func (s *server) handleUploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
sess, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
||||
return
|
||||
}
|
||||
_ = sess
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize+1024)
|
||||
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "file too large or invalid multipart")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "file field is required")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Проверка опасного имени ДО filepath.Base
|
||||
rawName := header.Filename
|
||||
if strings.Contains(rawName, "..") || strings.ContainsAny(rawName, "/\\") || strings.HasPrefix(filepath.Base(rawName), ".") {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "dangerous filename rejected")
|
||||
return
|
||||
}
|
||||
filename := filepath.Base(rawName)
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(file, maxUploadSize+1))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "read failed")
|
||||
return
|
||||
}
|
||||
if int64(len(data)) > maxUploadSize {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "file exceeds 10 MiB limit")
|
||||
return
|
||||
}
|
||||
|
||||
contentType := detectMIME(data)
|
||||
if contentType != "image/png" && contentType != "image/jpeg" {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "only PNG and JPEG allowed")
|
||||
return
|
||||
}
|
||||
|
||||
if contentType == "image/jpeg" || contentType == "image/png" {
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "cannot decode image dimensions")
|
||||
return
|
||||
}
|
||||
if int64(cfg.Width)*int64(cfg.Height) > maxPixels {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "image exceeds 40 million pixels")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
keyBytes := make([]byte, 16)
|
||||
rand.Read(keyBytes)
|
||||
s3Key := hex.EncodeToString(keyBytes)
|
||||
|
||||
hash := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(hash[:])
|
||||
|
||||
// Таймаут 5 секунд для S3 — чтобы быстро вернуть 503, а не ждать 504 от HAProxy
|
||||
s3Ctx, s3Cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer s3Cancel()
|
||||
|
||||
err = s3.UploadFile(s3Ctx, s.s3Client, s.s3Bucket, s3Key, bytes.NewReader(data), int64(len(data)), contentType)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "s3_unavailable", "S3 storage unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
// ИСПРАВЛЕНО: используем r.Context() вместо несуществующего ctx
|
||||
var attID int64
|
||||
err = s.db.QueryRowContext(r.Context(),
|
||||
`INSERT INTO attachments (s3_key, filename, content_type, size, checksum)
|
||||
VALUES ($1, $2, $3, $4, $5) RETURNING id`,
|
||||
s3Key, filename, contentType, len(data), checksum).Scan(&attID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "metadata save failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": attID,
|
||||
"filename": filename,
|
||||
"content_type": contentType,
|
||||
"size": len(data),
|
||||
"checksum": checksum,
|
||||
"status": "ready",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
sess, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
||||
return
|
||||
}
|
||||
|
||||
idStr := strings.TrimPrefix(r.URL.Path, "/api/attachments/")
|
||||
attID, err := strconv.ParseInt(idStr, 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "invalid attachment id")
|
||||
return
|
||||
}
|
||||
|
||||
var s3Key, filename, contentType string
|
||||
var size int64
|
||||
var messageID sql.NullInt64
|
||||
var uploaderUserID sql.NullInt64
|
||||
err = s.db.QueryRowContext(r.Context(),
|
||||
`SELECT a.s3_key, a.filename, a.content_type, a.size, a.message_id,
|
||||
(SELECT sender_id FROM messages WHERE id = a.message_id)
|
||||
FROM attachments a WHERE a.id = $1`,
|
||||
attID).Scan(&s3Key, &filename, &contentType, &size, &messageID, &uploaderUserID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "attachment not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// Fallback: если в таблице нет колонки uploader — используем простой запрос
|
||||
err = s.db.QueryRowContext(r.Context(),
|
||||
`SELECT s3_key, filename, content_type, size, message_id FROM attachments WHERE id = $1`,
|
||||
attID).Scan(&s3Key, &filename, &contentType, &size, &messageID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "attachment not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "query failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка прав доступа
|
||||
if messageID.Valid {
|
||||
var senderID int64
|
||||
var recipient string
|
||||
err = s.db.QueryRowContext(r.Context(),
|
||||
`SELECT sender_id, recipient FROM messages WHERE id = $1`, messageID.Int64).Scan(&senderID, &recipient)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "not_found", "message not found")
|
||||
return
|
||||
}
|
||||
if senderID != sess.UserID && recipient != sess.Login {
|
||||
writeError(w, http.StatusForbidden, "forbidden", "access denied")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Таймаут 5 секунд для S3
|
||||
s3Ctx, s3Cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer s3Cancel()
|
||||
|
||||
obj, err := s3.DownloadFile(s3Ctx, s.s3Client, s.s3Bucket, s3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "s3_unavailable", "S3 storage unavailable")
|
||||
return
|
||||
}
|
||||
defer obj.Close()
|
||||
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, obj)
|
||||
}
|
||||
|
||||
func detectMIME(data []byte) string {
|
||||
if len(data) >= 8 && data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47 {
|
||||
return "image/png"
|
||||
}
|
||||
if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
|
||||
return "image/jpeg"
|
||||
}
|
||||
return http.DetectContentType(data)
|
||||
}
|
||||
|
||||
func (s *server) authenticate(r *http.Request) (*session, error) {
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
|
||||
Reference in New Issue
Block a user