forked from mtusi2026/mtusi2026lab6
Prepare verified laboratory 6 implementation and evidence
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
var ErrTooLarge = errors.New("image too large")
|
||||
var ErrUnsupported = errors.New("invalid image or MIME")
|
||||
|
||||
type File struct {
|
||||
*os.File
|
||||
Size int64
|
||||
SHA256, ContentType string
|
||||
}
|
||||
|
||||
func (f *File) Dispose() { _ = f.Close(); _ = os.Remove(f.Name()) }
|
||||
func Inspect(body io.Reader, filename, mime string) (out *File, err error) {
|
||||
if err = model.ValidateFilename(filename); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mime != "image/png" && mime != "image/jpeg" {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
f, e := os.CreateTemp("", "messenger-upload-*")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(f.Name())
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
n, e := io.Copy(io.MultiWriter(f, hash), io.LimitReader(body, model.MaxImageBytes+1))
|
||||
if e != nil {
|
||||
return nil, &model.ValidationError{Message: "incomplete image upload"}
|
||||
}
|
||||
if n > model.MaxImageBytes {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
cfg, format, e := image.DecodeConfig(f)
|
||||
if e != nil || "image/"+format != mime {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if cfg.Width < 1 || cfg.Height < 1 || pixels > model.MaxImagePixels {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
decoded, actual, e := image.Decode(f)
|
||||
if e != nil || actual != format || decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return &File{f, n, hex.EncodeToString(hash.Sum(nil)), mime}, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func pngBytes(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var b bytes.Buffer
|
||||
if e := png.Encode(&b, image.NewNRGBA(image.Rect(0, 0, 3, 2))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
func TestOriginalBytesArePreserved(t *testing.T) {
|
||||
raw := pngBytes(t)
|
||||
f, e := Inspect(bytes.NewReader(raw), "пример.png", "image/png")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer f.Dispose()
|
||||
got, e := io.ReadAll(f)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !bytes.Equal(got, raw) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
}
|
||||
func TestRejectsInvalidImageAndFilename(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, mime string
|
||||
body []byte
|
||||
want error
|
||||
}{
|
||||
{"a.png", "image/jpeg", pngBytes(t), ErrUnsupported},
|
||||
{"a.png", "image/png", []byte("not an image"), ErrUnsupported},
|
||||
{"a.png", "application/octet-stream", pngBytes(t), ErrUnsupported},
|
||||
{"a.png", "image/png", append(pngBytes(t)[:20], 0), ErrUnsupported},
|
||||
} {
|
||||
t.Run(tc.mime+string(tc.body[:1]), func(t *testing.T) {
|
||||
_, e := Inspect(bytes.NewReader(tc.body), tc.name, tc.mime)
|
||||
if !errors.Is(e, tc.want) {
|
||||
t.Fatalf("got %v, want %v", e, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, name := range []string{"../x.png", "a\\b", "a\x00b", "a\nb", ""} {
|
||||
if _, e := Inspect(bytes.NewReader(pngBytes(t)), name, "image/png"); e == nil {
|
||||
t.Fatalf("accepted unsafe filename %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRejectsOversizedStreamBeforeDecoding(t *testing.T) {
|
||||
_, e := Inspect(io.LimitReader(zeroReader{}, model.MaxImageBytes+1), "a.png", "image/png")
|
||||
if !errors.Is(e, ErrTooLarge) {
|
||||
t.Fatalf("got %v", e)
|
||||
}
|
||||
}
|
||||
|
||||
type zeroReader struct{}
|
||||
|
||||
func (zeroReader) Read(p []byte) (int, error) { clear(p); return len(p), nil }
|
||||
func TestRejectsPixelBombBeforeDecoding(t *testing.T) {
|
||||
raw := pngBytes(t)
|
||||
binary.BigEndian.PutUint32(raw[16:20], 50000)
|
||||
binary.BigEndian.PutUint32(raw[20:24], 50000)
|
||||
binary.BigEndian.PutUint32(raw[29:33], crc32.ChecksumIEEE(raw[12:29]))
|
||||
_, e := Inspect(bytes.NewReader(raw), "huge.png", "image/png")
|
||||
if !errors.Is(e, ErrTooLarge) {
|
||||
t.Fatalf("pixel limit did not apply before decode: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/password"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A normal PNG encoder allocates several full-width filter rows itself.
|
||||
// Construct a tiny, highly compressible adversarial fixture as a stream instead.
|
||||
func extremePNG(t *testing.T, interlaced bool) []byte {
|
||||
t.Helper()
|
||||
const width = 40_000_000
|
||||
const height = 1
|
||||
var idat bytes.Buffer
|
||||
z := zlib.NewWriter(&idat)
|
||||
passes := [][4]int{{0, 0, 1, 1}}
|
||||
if interlaced {
|
||||
passes = [][4]int{{0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4}, {0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2}}
|
||||
}
|
||||
for _, p := range passes {
|
||||
w := (width - p[0] + p[2] - 1) / p[2]
|
||||
h := (height - p[1] + p[3] - 1) / p[3]
|
||||
if width <= p[0] || height <= p[1] || w <= 0 || h <= 0 {
|
||||
continue
|
||||
}
|
||||
for row := 0; row < h; row++ {
|
||||
if _, e := z.Write([]byte{0}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := io.CopyN(z, zeroReader{}, int64(w)*8); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if e := z.Close(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
out.Write([]byte{137, 80, 78, 71, 13, 10, 26, 10})
|
||||
chunk := func(kind string, data []byte) {
|
||||
var word [4]byte
|
||||
binary.BigEndian.PutUint32(word[:], uint32(len(data)))
|
||||
out.Write(word[:])
|
||||
out.WriteString(kind)
|
||||
out.Write(data)
|
||||
crc := crc32.NewIEEE()
|
||||
_, _ = crc.Write([]byte(kind))
|
||||
_, _ = crc.Write(data)
|
||||
binary.BigEndian.PutUint32(word[:], crc.Sum32())
|
||||
out.Write(word[:])
|
||||
}
|
||||
header := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(header[:4], width)
|
||||
binary.BigEndian.PutUint32(header[4:8], height)
|
||||
header[8] = 16
|
||||
header[9] = 6
|
||||
if interlaced {
|
||||
header[12] = 1
|
||||
}
|
||||
chunk("IHDR", header)
|
||||
chunk("IDAT", idat.Bytes())
|
||||
chunk("IEND", nil)
|
||||
return out.Bytes()
|
||||
}
|
||||
func TestWorstCaseImagesWithinBudget(t *testing.T) {
|
||||
if os.Getenv("RUN_IMAGE_STRESS") != "1" {
|
||||
t.Skip("explicit isolated memory experiment required")
|
||||
}
|
||||
old := debug.SetMemoryLimit(1536 * 1024 * 1024)
|
||||
defer debug.SetMemoryLimit(old)
|
||||
for _, interlaced := range []bool{false, true} {
|
||||
raw := extremePNG(t, interlaced)
|
||||
runtime.GC()
|
||||
stop := make(chan struct{})
|
||||
var workers sync.WaitGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
if _, e := password.New().Hash("synthetic-concurrent-KDF"); e != nil {
|
||||
t.Error(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for repeat := 0; repeat < 2; repeat++ {
|
||||
f, e := Inspect(bytes.NewReader(raw), "wide.png", "image/png")
|
||||
if e != nil {
|
||||
close(stop)
|
||||
workers.Wait()
|
||||
t.Fatal(e)
|
||||
}
|
||||
f.Dispose()
|
||||
}
|
||||
close(stop)
|
||||
workers.Wait()
|
||||
runtime.GC()
|
||||
}
|
||||
raw, e := os.ReadFile("/proc/self/status")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
peak := int64(0)
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if strings.HasPrefix(line, "VmHWM:") {
|
||||
fields := strings.Fields(line)
|
||||
peak, e = strconv.ParseInt(fields[1], 10, 64)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if peak <= 0 || peak >= 2*1024*1024 {
|
||||
t.Fatalf("RSS high-water mark out of budget: %d KiB", peak)
|
||||
}
|
||||
t.Logf("PASS native RGBA64 40000000x1, normal+Adam7, two sequential validations each, 3 concurrent Argon2 workers; peak_rss_kib=%d hard_limit_kib=2097152", peak)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func FitDimensions(w, h, max int) (int, int) {
|
||||
if w <= max && h <= max {
|
||||
return w, h
|
||||
}
|
||||
if w >= h {
|
||||
return max, maxInt(1, h*max/w)
|
||||
}
|
||||
return maxInt(1, w*max/h), max
|
||||
}
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
type Transformer struct{}
|
||||
|
||||
func NewTransformer() port.Transformer { return Transformer{} }
|
||||
|
||||
// ImageMagick is a constrained subprocess; no input names or shell fragments are accepted.
|
||||
func (Transformer) Transform(ctx context.Context, r io.Reader) ([]port.ProcessedVariant, error) {
|
||||
input, err := os.CreateTemp("", "pipeline-original-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = input.Close(); _ = os.Remove(input.Name()) }()
|
||||
n, err := io.Copy(input, io.LimitReader(r, model.MaxImageBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n > model.MaxImageBytes {
|
||||
return nil, model.ErrInvalidImage
|
||||
}
|
||||
if _, err = input.Seek(0, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config, _, err := image.DecodeConfig(input)
|
||||
if err != nil || int64(config.Width)*int64(config.Height) > model.MaxImagePixels {
|
||||
return nil, model.ErrInvalidImage
|
||||
}
|
||||
probe := exec.CommandContext(ctx, "convert", "-limit", "memory", "256MiB", "-limit", "map", "256MiB", "-limit", "disk", "0", input.Name()+"[0]", "-auto-orient", "-format", "%w %h", "info:")
|
||||
raw, err := probe.Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("image subprocess unavailable: %w", err)
|
||||
}
|
||||
var originalW, originalH int
|
||||
if _, err = fmt.Sscanf(string(raw), "%d %d", &originalW, &originalH); err != nil || int64(originalW)*int64(originalH) > model.MaxImagePixels {
|
||||
return nil, model.ErrInvalidImage
|
||||
}
|
||||
var variants []port.ProcessedVariant
|
||||
for _, v := range []struct {
|
||||
name, mime, geometry, format string
|
||||
crop bool
|
||||
}{{"thumbnail", "image/jpeg", "256x256>", "jpeg", false}, {"crop", "image/jpeg", "128x128^", "jpeg", true}, {"optimized", "image/webp", "1280x1280>", "webp", false}} {
|
||||
geometry := v.geometry
|
||||
if !v.crop {
|
||||
max := 256
|
||||
if v.name == "optimized" {
|
||||
max = 1280
|
||||
}
|
||||
w, h := FitDimensions(originalW, originalH, max)
|
||||
geometry = fmt.Sprintf("%dx%d!", w, h)
|
||||
}
|
||||
args := []string{"-limit", "memory", "256MiB", "-limit", "map", "256MiB", "-limit", "disk", "0", "-limit", "thread", "1", input.Name() + "[0]", "-auto-orient", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "-resize", geometry}
|
||||
if v.crop {
|
||||
args = append(args, "-gravity", "center", "-extent", "128x128")
|
||||
}
|
||||
args = append(args, "-quality", "82", v.format+":-")
|
||||
cmd := exec.CommandContext(ctx, "convert", args...)
|
||||
var out limitedBuffer
|
||||
cmd.Stdout = &out
|
||||
if err = cmd.Run(); err != nil {
|
||||
return nil, fmt.Errorf("image subprocess failed: %w", err)
|
||||
}
|
||||
b := out.Bytes()
|
||||
if len(b) == 0 {
|
||||
return nil, fmt.Errorf("empty variant")
|
||||
}
|
||||
w, h := 0, 0
|
||||
if v.format == "webp" {
|
||||
// Read only geometry through the native decoder; never dump diagnostics/payload.
|
||||
probe := exec.CommandContext(ctx, "identify", "-format", "%w %h", "webp:-")
|
||||
probe.Stdin = bytes.NewReader(b)
|
||||
raw, e := probe.Output()
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("invalid generated WebP")
|
||||
}
|
||||
if _, e = fmt.Sscanf(string(raw), "%d %d", &w, &h); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
} else {
|
||||
// JPEG dimensions are read through the same strict decoder used for uploads.
|
||||
cfg, _, e := image.DecodeConfig(bytes.NewReader(b))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
w, h = cfg.Width, cfg.Height
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
variants = append(variants, port.ProcessedVariant{Metadata: model.Variant{Name: v.name, ContentType: v.mime, SHA256: hex.EncodeToString(sum[:]), SizeBytes: int64(len(b)), Width: w, Height: h}, Bytes: b})
|
||||
}
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
type limitedBuffer struct{ bytes.Buffer }
|
||||
|
||||
func (b *limitedBuffer) Write(p []byte) (int, error) {
|
||||
if b.Len()+len(p) > 16*1024*1024 {
|
||||
return 0, fmt.Errorf("variant too large")
|
||||
}
|
||||
return b.Buffer.Write(p)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package imagefile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestActualVariantsHonorDimensionsAlphaAndEXIF(t *testing.T) {
|
||||
if os.Getenv("RUN_VARIANT_TESTS") != "1" {
|
||||
t.Skip("requires actual ImageMagick runtime")
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
w, h int
|
||||
orientation bool
|
||||
}{{"landscape", 320, 200, false}, {"tiny", 1, 1, false}, {"portrait", 23, 67, false}, {"exif", 40, 20, true}} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
img := image.NewNRGBA(image.Rect(0, 0, c.w, c.h))
|
||||
img.Set(0, 0, color.NRGBA{R: 255, A: 0})
|
||||
var encoded bytes.Buffer
|
||||
if c.orientation {
|
||||
if e := jpeg.Encode(&encoded, img, &jpeg.Options{Quality: 82}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
} else {
|
||||
if e := png.Encode(&encoded, img); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
input := encoded.Bytes()
|
||||
if c.orientation {
|
||||
payload := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 18, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
|
||||
marker := append([]byte{255, 225, 0, byte(len(payload) + 2)}, payload...)
|
||||
input = append(append(append([]byte{}, input[:2]...), marker...), input[2:]...)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
variants, e := NewTransformer().Transform(ctx, bytes.NewReader(input))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(variants) != 3 {
|
||||
t.Fatalf("want three variants, got %d", len(variants))
|
||||
}
|
||||
w, h := c.w, c.h
|
||||
if c.orientation {
|
||||
w, h = h, w
|
||||
}
|
||||
for _, v := range variants {
|
||||
s := sha256.Sum256(v.Bytes)
|
||||
if v.Metadata.SHA256 != hex.EncodeToString(s[:]) || v.Metadata.SizeBytes != int64(len(v.Bytes)) {
|
||||
t.Fatal("content digest/size mismatch")
|
||||
}
|
||||
wantW, wantH := w, h
|
||||
if v.Metadata.Name == "thumbnail" {
|
||||
wantW, wantH = FitDimensions(w, h, 256)
|
||||
}
|
||||
if v.Metadata.Name == "crop" {
|
||||
wantW, wantH = 128, 128
|
||||
}
|
||||
if v.Metadata.Width != wantW || v.Metadata.Height != wantH {
|
||||
t.Fatalf("%s: got %dx%d want %dx%d", v.Metadata.Name, v.Metadata.Width, v.Metadata.Height, wantW, wantH)
|
||||
}
|
||||
if v.Metadata.ContentType == "image/jpeg" {
|
||||
decoded, e := jpeg.Decode(bytes.NewReader(v.Bytes))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if decoded.Bounds().Dx() != wantW || decoded.Bounds().Dy() != wantH {
|
||||
t.Fatal("actual JPEG geometry mismatch")
|
||||
}
|
||||
if !c.orientation {
|
||||
r, g, b, _ := decoded.At(0, 0).RGBA()
|
||||
if r < 64000 || g < 64000 || b < 64000 {
|
||||
t.Fatal("alpha was not composited on white")
|
||||
}
|
||||
}
|
||||
} else if len(v.Bytes) < 16 || string(v.Bytes[:4]) != "RIFF" || string(v.Bytes[8:12]) != "WEBP" {
|
||||
t.Fatal("optimized file is not WebP")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package imagefile
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFitDimensionsPreservesAspectAndDoesNotUpscale(t *testing.T) {
|
||||
for _, c := range []struct{ w, h, max, wantW, wantH int }{{320, 200, 256, 256, 160}, {1, 1, 256, 1, 1}, {1, 400, 256, 1, 256}, {400, 1, 256, 256, 1}, {200, 320, 256, 160, 256}, {1280, 1280, 1280, 1280, 1280}} {
|
||||
w, h := FitDimensions(c.w, c.h, c.max)
|
||||
if w != c.wantW || h != c.wantH {
|
||||
t.Errorf("%+v: got %dx%d", c, w, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user