Выполнение lab4 на 4

This commit is contained in:
Daria0w0
2026-11-06 17:35:48 +03:00
parent 9197e151ba
commit 879463c947
89 changed files with 5551 additions and 108 deletions
+156
View File
@@ -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
}
+142
View File
@@ -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 }