forked from mtusi2026/mtusi2026lab4
feat(app) implemented lab 4
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
// Package attachments implements the synchronous upload, metadata lookup and
|
||||
// authorized download path for chat attachments.
|
||||
package attachments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
type Validator struct {
|
||||
maxPixels int64
|
||||
decodeBudget *semaphore.Weighted
|
||||
budgetBytes int64
|
||||
}
|
||||
|
||||
type ImageInfo struct {
|
||||
ContentType string
|
||||
Width int
|
||||
Height int
|
||||
}
|
||||
|
||||
func NewValidator(maxPixels, decodeBudgetBytes int64) *Validator {
|
||||
return &Validator{
|
||||
maxPixels: maxPixels,
|
||||
decodeBudget: semaphore.NewWeighted(decodeBudgetBytes),
|
||||
budgetBytes: decodeBudgetBytes,
|
||||
}
|
||||
}
|
||||
|
||||
// Validate checks the declared media type against the real bytes and then
|
||||
// decodes the image under a shared memory budget. The decode is what turns a
|
||||
// structurally broken or truncated file into 415 instead of a saved object.
|
||||
//
|
||||
// AGENT: image.DecodeConfig first reads only the header. This is the important
|
||||
// ordering: a decompression bomb is rejected from width×height before the
|
||||
// decoder is allowed to allocate pixel memory.
|
||||
func (v *Validator) Validate(ctx context.Context, file *os.File, declared string) (ImageInfo, error) {
|
||||
mediaType, _, err := mime.ParseMediaType(declared)
|
||||
if err != nil {
|
||||
return ImageInfo{}, common.UnsupportedMedia("Content-Type must be image/png or image/jpeg")
|
||||
}
|
||||
if mediaType != "image/png" && mediaType != "image/jpeg" {
|
||||
return ImageInfo{}, common.UnsupportedMedia("Content-Type must be image/png or image/jpeg")
|
||||
}
|
||||
|
||||
if _, err = file.Seek(0, 0); err != nil {
|
||||
return ImageInfo{}, common.BadRequest("cannot read upload body")
|
||||
}
|
||||
head := make([]byte, 512)
|
||||
n, readErr := file.Read(head)
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
return ImageInfo{}, common.BadRequest("cannot read upload body")
|
||||
}
|
||||
detected := http.DetectContentType(head[:n])
|
||||
if detected != mediaType {
|
||||
return ImageInfo{}, common.UnsupportedMedia("file content does not match Content-Type")
|
||||
}
|
||||
|
||||
if _, err = file.Seek(0, 0); err != nil {
|
||||
return ImageInfo{}, common.BadRequest("cannot read upload body")
|
||||
}
|
||||
config, format, err := image.DecodeConfig(file)
|
||||
if err != nil {
|
||||
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
|
||||
}
|
||||
if format != "png" && format != "jpeg" {
|
||||
return ImageInfo{}, common.UnsupportedMedia("only PNG and JPEG images are accepted")
|
||||
}
|
||||
if (format == "png" && mediaType != "image/png") || (format == "jpeg" && mediaType != "image/jpeg") {
|
||||
return ImageInfo{}, common.UnsupportedMedia("file content does not match Content-Type")
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 {
|
||||
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
|
||||
}
|
||||
|
||||
pixels := int64(config.Width) * int64(config.Height)
|
||||
if pixels <= 0 || pixels > v.maxPixels {
|
||||
return ImageInfo{}, common.PayloadTooLarge("image has too many pixels")
|
||||
}
|
||||
|
||||
// Approximate decoded RGBA size. The semaphore caps the sum across
|
||||
// concurrent requests; a single 40 Mp image needs ~160 MiB, so a lower
|
||||
// configured budget is a deliberate operator choice and becomes a 413.
|
||||
weight := pixels * 4
|
||||
if weight > v.budgetBytes {
|
||||
return ImageInfo{}, common.PayloadTooLarge("image is too large to validate")
|
||||
}
|
||||
if err = v.decodeBudget.Acquire(ctx, weight); err != nil {
|
||||
return ImageInfo{}, common.Unavailable("image validation is busy")
|
||||
}
|
||||
defer v.decodeBudget.Release(weight)
|
||||
|
||||
if _, err = file.Seek(0, 0); err != nil {
|
||||
return ImageInfo{}, common.BadRequest("cannot read upload body")
|
||||
}
|
||||
info, decodeErr := safeDecode(file)
|
||||
if decodeErr != nil {
|
||||
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
|
||||
}
|
||||
bounds := info.Bounds()
|
||||
if bounds.Dx() != config.Width || bounds.Dy() != config.Height {
|
||||
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
|
||||
}
|
||||
|
||||
return ImageInfo{ContentType: mediaType, Width: config.Width, Height: config.Height}, nil
|
||||
}
|
||||
|
||||
// safeDecode converts a decoder panic into an ordinary error. A malformed
|
||||
// client file must never crash the process or become a 500.
|
||||
func safeDecode(file *os.File) (img image.Image, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
img = nil
|
||||
err = errors.New("image decoder panic")
|
||||
}
|
||||
}()
|
||||
img, _, err = image.Decode(file)
|
||||
return img, err
|
||||
}
|
||||
Reference in New Issue
Block a user