upload.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Package handlers
  2. package handlers
  3. import (
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/minio/minio-go/v7"
  16. "github.com/minio/minio-go/v7/pkg/credentials"
  17. )
  18. const maxUploadSize = 10 << 20 // 10 MB
  19. type UploadHandler struct {
  20. minioClient *minio.Client
  21. bucket string
  22. endpoint string
  23. publicEndpoint string
  24. }
  25. func NewUploadHandler(endpoint, publicEndpoint, accessKey, secretKey, bucket string, useSSL bool) (*UploadHandler, error) {
  26. client, err := minio.New(endpoint, &minio.Options{
  27. Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
  28. Secure: useSSL,
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. return &UploadHandler{
  34. minioClient: client,
  35. bucket: bucket,
  36. endpoint: endpoint,
  37. publicEndpoint: publicEndpoint,
  38. }, nil
  39. }
  40. type presignedURLRequest struct {
  41. ContentType string `json:"content_type"`
  42. MaxSizeMB int `json:"max_size_mb"`
  43. }
  44. type presignedURLResponse struct {
  45. UploadURL string `json:"upload_url"`
  46. FileURL string `json:"file_url"`
  47. Fields map[string]string `json:"fields"`
  48. }
  49. func (h *UploadHandler) UploadFile(w http.ResponseWriter, r *http.Request) {
  50. r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
  51. if err := r.ParseMultipartForm(maxUploadSize); err != nil {
  52. writeError(w, http.StatusBadRequest, "file too large or invalid multipart", err)
  53. return
  54. }
  55. file, header, err := r.FormFile("file")
  56. if err != nil {
  57. writeError(w, http.StatusBadRequest, "file is required", err)
  58. return
  59. }
  60. defer file.Close()
  61. contentType := header.Header.Get("Content-Type")
  62. validContentTypes := map[string]bool{
  63. "image/jpeg": true, "image/png": true, "image/webp": true, "image/heic": true,
  64. }
  65. if !validContentTypes[contentType] {
  66. writeError(w, http.StatusBadRequest, "unsupported content type", nil)
  67. return
  68. }
  69. // Заголовок Content-Type подделывается клиентом — проверяем реальную
  70. // сигнатуру файла по первым байтам, чтобы нельзя было залить произвольный
  71. // контент под видом изображения.
  72. if err := verifyImageSignature(file, contentType); err != nil {
  73. writeError(w, http.StatusBadRequest, "file content does not match declared image type", err)
  74. return
  75. }
  76. ext := ".jpg"
  77. switch contentType {
  78. case "image/png":
  79. ext = ".png"
  80. case "image/webp":
  81. ext = ".webp"
  82. case "image/heic":
  83. ext = ".heic"
  84. }
  85. objectName := "uploads/" + uuid.New().String() + ext
  86. _, err = h.minioClient.PutObject(r.Context(), h.bucket, objectName, file, header.Size,
  87. minio.PutObjectOptions{ContentType: contentType},
  88. )
  89. if err != nil {
  90. writeError(w, http.StatusInternalServerError, "failed to upload file", err)
  91. return
  92. }
  93. fileURL := fmt.Sprintf("%s/%s/%s", h.publicEndpoint, h.bucket, objectName)
  94. writeJSON(w, http.StatusOK, map[string]string{
  95. "file_url": fileURL,
  96. })
  97. }
  98. func (h *UploadHandler) PresignedURL(w http.ResponseWriter, r *http.Request) {
  99. var req presignedURLRequest
  100. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  101. writeError(w, http.StatusBadRequest, "invalid request body", err)
  102. return
  103. }
  104. if req.MaxSizeMB <= 0 || req.MaxSizeMB > 50 {
  105. req.MaxSizeMB = 10
  106. }
  107. validContentTypes := map[string]bool{
  108. "image/jpeg": true, "image/png": true, "image/webp": true, "image/heic": true,
  109. }
  110. if !validContentTypes[req.ContentType] {
  111. writeError(w, http.StatusBadRequest, "unsupported content type", nil)
  112. return
  113. }
  114. fileID := uuid.New().String()
  115. ext := ".jpg"
  116. switch req.ContentType {
  117. case "image/png":
  118. ext = ".png"
  119. case "image/webp":
  120. ext = ".webp"
  121. case "image/heic":
  122. ext = ".heic"
  123. }
  124. objectName := "uploads/" + fileID + ext
  125. policy := minio.NewPostPolicy()
  126. policy.SetBucket(h.bucket)
  127. policy.SetKey(objectName)
  128. policy.SetExpires(time.Now().Add(15 * time.Minute))
  129. policy.SetContentType(req.ContentType)
  130. policy.SetContentLengthRange(1, int64(req.MaxSizeMB)*1024*1024)
  131. uploadURL, formData, err := h.minioClient.PresignedPostPolicy(r.Context(), policy)
  132. if err != nil {
  133. writeError(w, http.StatusInternalServerError, "failed to generate upload URL", err)
  134. return
  135. }
  136. // Replace internal endpoint (minio:9000) with public endpoint for browser uploads
  137. publicUploadURL := uploadURL
  138. uploadURLStr := h.publicEndpoint + uploadURL.Path + "?" + uploadURL.RawQuery
  139. if parsed, err := url.Parse(uploadURLStr); err == nil {
  140. publicUploadURL = parsed
  141. }
  142. fileURL := h.publicEndpoint + "/" + h.bucket + "/" + objectName
  143. writeJSON(w, http.StatusOK, presignedURLResponse{
  144. UploadURL: publicUploadURL.String(),
  145. FileURL: fileURL,
  146. Fields: formData,
  147. })
  148. }
  149. // verifyImageSignature читает первые байты файла и проверяет, что реальная
  150. // сигнатура соответствует заявленному content-type. После проверки возвращает
  151. // курсор файла в начало, чтобы последующая загрузка читала его целиком.
  152. func verifyImageSignature(file io.ReadSeeker, declaredType string) error {
  153. head := make([]byte, 512)
  154. n, err := io.ReadFull(file, head)
  155. if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
  156. return fmt.Errorf("read file header: %w", err)
  157. }
  158. head = head[:n]
  159. if _, err := file.Seek(0, io.SeekStart); err != nil {
  160. return fmt.Errorf("seek file start: %w", err)
  161. }
  162. if !matchesImageType(head, declaredType) {
  163. return errors.New("file signature mismatch")
  164. }
  165. return nil
  166. }
  167. // matchesImageType сверяет байтовую сигнатуру с заявленным типом.
  168. // net/http.DetectContentType умеет распознавать jpeg/png/webp, но не heic,
  169. // поэтому для heic проверяем ISO-BMFF бокс ftyp вручную.
  170. func matchesImageType(head []byte, declaredType string) bool {
  171. if declaredType == "image/heic" {
  172. return isHEIC(head)
  173. }
  174. return http.DetectContentType(head) == declaredType
  175. }
  176. // isHEIC проверяет, что файл — ISO Base Media File Format с HEIF-брендом.
  177. func isHEIC(head []byte) bool {
  178. if len(head) < 12 || !bytes.Equal(head[4:8], []byte("ftyp")) {
  179. return false
  180. }
  181. brand := string(head[8:12])
  182. switch brand {
  183. case "heic", "heix", "hevc", "heim", "heis", "mif1", "msf1":
  184. return true
  185. }
  186. return false
  187. }
  188. func (h *UploadHandler) DeleteObjects(ctx context.Context, urls []string) error {
  189. prefix := h.publicEndpoint + "/" + h.bucket + "/"
  190. for _, fileURL := range urls {
  191. if !strings.HasPrefix(fileURL, prefix) {
  192. continue
  193. }
  194. objectKey := strings.TrimPrefix(fileURL, prefix)
  195. if err := h.minioClient.RemoveObject(ctx, h.bucket, objectKey, minio.RemoveObjectOptions{}); err != nil {
  196. return fmt.Errorf("delete object %s: %w", objectKey, err)
  197. }
  198. }
  199. return nil
  200. }