| 1 | package browser |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "image/png" |
| 6 | "io" |
| 7 | "os" |
| 8 | ) |
| 9 | |
| 10 | const screenshotMaxPixels = 16_777_216 |
| 11 | |
| 12 | // Validate before either image admission or the oversize-file response. An empty |
| 13 | // or corrupt host artifact must never be described as a successful screenshot. |
| 14 | func validateScreenshot(f *os.File, shot Screenshot) error { |
| 15 | if shot.MIME != "" && shot.MIME != "image/png" { |
| 16 | return fmt.Errorf("invalid_image: screenshot MIME is not image/png") |
| 17 | } |
| 18 | config, err := png.DecodeConfig(io.LimitReader(f, 1<<20)) |
| 19 | if err != nil { |
| 20 | return fmt.Errorf("invalid_image: invalid PNG header: %w", err) |
| 21 | } |
| 22 | if config.Width <= 0 || config.Height <= 0 || int64(config.Width)*int64(config.Height) > screenshotMaxPixels { |
| 23 | return fmt.Errorf("invalid_image: screenshot exceeds the pixel budget") |
| 24 | } |
| 25 | if config.Width != shot.Width || config.Height != shot.Height { |
| 26 | return fmt.Errorf("invalid_image: screenshot dimensions %dx%d disagree with host %dx%d", config.Width, config.Height, shot.Width, shot.Height) |
| 27 | } |
| 28 | if _, err := f.Seek(0, io.SeekStart); err != nil { |
| 29 | return err |
| 30 | } |
| 31 | if _, err := png.Decode(io.LimitReader(f, 64<<20)); err != nil { |
| 32 | return fmt.Errorf("invalid_image: screenshot PNG cannot be decoded: %w", err) |
| 33 | } |
| 34 | _, err = f.Seek(0, io.SeekStart) |
| 35 | return err |
| 36 | } |
| 37 |