package slidestest
// An agent's pictures through the drive API (internal/slides/agent_assets.go):
// POST /api/v1/decks/{sqid}/assets takes the image bytes as the body,
// judges them, keeps them under their own hash, verifies them for the
// deck and registers them as an asset of it, as the agent.
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"golang.org/x/image/webp"
)
// webpPicture is a 4 by 3 lossless WebP of one flat colour (the export
// test's fixture): Go has no WebP encoder, so the bytes are written out.
func webpPicture(t *testing.T) []byte {
t.Helper()
raw, err := hex.DecodeString("524946461e000000574542505650384c110000002f0380000007508f2217a5ff8188e87f0000")
if err != nil {
t.Fatal(err)
}
return raw
}
// jpegPicture is a w by h JPEG of one colour.
func jpegPicture(t *testing.T, w, h int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i := range img.Pix {
img.Pix[i] = 0x80
}
img.Set(0, 0, color.Black)
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, nil); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// hugeWebP is forty bytes whose header says 30000 by 30000 with alpha
// (the svg package's HugeWebP): a decode would allocate 900 MB.
func hugeWebP() []byte {
edge := 30000
b := []byte("RIFF\x20\x00\x00\x00WEBPVP8X\x0a\x00\x00\x00\x10\x00\x00\x00" +
"\x00\x00\x00\x00\x00\x00ALPH\x02\x00\x00\x00\x00\x00")
for _, at := range []int{24, 27} {
b[at], b[at+1], b[at+2] = byte(edge-1), byte((edge-1)>>8), byte((edge-1)>>16)
}
return b
}
// postPicture is one upload: the bytes as the body, under the token.
func postPicture(t *testing.T, a *testApp, sqid, token, query string, body []byte) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/decks/"+sqid+"/assets"+query, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/octet-stream")
return send(t, a, req)
}
func jsonObject(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Fatalf("Content-Type = %q, want JSON\n%s", ct, rec.Body)
}
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("body is not a JSON object: %v\n%s", err, rec.Body)
}
return out
}
type agentAsset struct {
Ref string `json:"ref"`
Name string `json:"name"`
Width int `json:"width"`
Height int `json:"height"`
Alt string `json:"alt"`
}
// deckAssets is the deck's assets as an agent reads them.
func deckAssets(t *testing.T, a *testApp, token, sqid string) map[string]agentAsset {
t.Helper()
rec := send(t, a, bearerRequest(t, http.MethodGet, "/api/v1/decks/"+sqid, token, ""))
if rec.Code != http.StatusOK {
t.Fatalf("GET deck: status %d\n%s", rec.Code, rec.Body)
}
var view struct {
Assets map[string]agentAsset `json:"assets"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil {
t.Fatal(err)
}
return view.Assets
}
// agentPictures is an app with a store, a signed-in person, their
// agent's token and a deck.
func agentPictures(t *testing.T) (a *testApp, cookies []*http.Cookie, token, sqid string) {
t.Helper()
cfg, mailer := newConfig(t)
cfg.AllowedAddresses = []string{allowedAddress, otherAddress}
cfg.Blobs = dirStore(t)
a = newAppWith(t, cfg, mailer)
cookies = signedIn(t, a, allowedAddress)
token = mintAgent(t, a, cookies, "pictures")
return a, cookies, token, apiDeck(t, a, token, "Pictures")
}
// TestAnAgentUploadsAPictureAndASlideDrawsIt: a PNG, a WebP and a JPEG go up,
// come back 201 with their hash and size, are registered as the
// agent's change, are served by the deck's picture route, and are drawn
// by the slide's HTML and its thumbnail once an image block names them.
func TestAnAgentUploadsAPictureAndASlideDrawsIt(t *testing.T) {
a, cookies, token, sqid := agentPictures(t)
for _, pic := range []struct {
name string
body []byte
width, height int
}{
{"png", onePixelPNG, 1, 1},
{"webp", webpPicture(t), 4, 3},
{"jpeg", jpegPicture(t, 5, 2), 5, 2},
} {
alt := "A " + pic.name + " picture"
rec := postPicture(t, a, sqid, token, "?alt="+url.QueryEscape(alt), pic.body)
if rec.Code != http.StatusCreated {
t.Fatalf("%s: status %d, want 201\n%s", pic.name, rec.Code, rec.Body)
}
out := jsonObject(t, rec)
ref := hashOf(pic.body)
if out["ref"] != ref || out["width"] != float64(pic.width) || out["height"] != float64(pic.height) {
t.Fatalf("%s: answered %v, want ref %s and %dx%d", pic.name, out, ref, pic.width, pic.height)
}
id, _ := out["id"].(string)
if id == "" {
t.Fatalf("%s: no asset id in %v", pic.name, out)
}
got, ok := deckAssets(t, a, token, sqid)[id]
if !ok || got != (agentAsset{Ref: ref, Name: got.Name, Width: pic.width, Height: pic.height, Alt: alt}) {
t.Fatalf("%s: the deck's asset %s is %+v (present %v)", pic.name, id, got, ok)
}
var actor string
if err := a.db.G.Raw("SELECT actor FROM deck_updates WHERE deck_id = (SELECT id FROM decks WHERE sqid = ?) ORDER BY seq DESC LIMIT 1", sqid).Scan(&actor).Error; err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(actor, "agent:") {
t.Errorf("%s: the registration's actor is %q, want the agent", pic.name, actor)
}
served := mustGet(t, a, "/d/"+sqid+"/assets/"+ref, http.StatusOK, cookies)
if !bytes.Equal(served.Body.Bytes(), pic.body) {
t.Errorf("%s: the served bytes differ from what went up", pic.name)
}
slide := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
`{"ops":[{"op":"add_slide","layout":"flow","template":"image-full"}]}`, http.StatusOK)
slideID := slide["ids"].(map[string]any)["0"].(string)
apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token,
fmt.Sprintf(`{"ops":[{"op":"add_block","slide":%q,"type":"image","region":"media","props":{"asset":%q}}]}`,
slideID, id), http.StatusOK)
page := mustGet(t, a, "/d/"+sqid+"/slides/"+slideID+".html", http.StatusOK, cookies).Body.String()
if !strings.Contains(page, `src="/d/`+sqid+`/assets/`+ref+`"`) {
t.Errorf("%s: the slide's HTML does not draw the picture:\n%s", pic.name, page)
}
thumb := mustGet(t, a, "/d/"+sqid+"/slides/"+slideID+".svg", http.StatusOK, cookies).Body.String()
// Inlined, since an SVG in an fetches nothing: a WebP as
// a PNG, the others as they are.
inline := "data:image/png;base64,"
if pic.name == "jpeg" {
inline = "data:image/jpeg;base64,"
}
if !strings.Contains(thumb, inline) {
t.Errorf("%s: the slide's SVG does not draw the picture:\n%s", pic.name, thumb)
}
}
}
// TestTheSamePictureTwiceIsOneAsset: the second upload answers 200 with
// the first one's ref and id, and the deck still has one asset.
func TestTheSamePictureTwiceIsOneAsset(t *testing.T) {
a, _, token, sqid := agentPictures(t)
first := postPicture(t, a, sqid, token, "", onePixelPNG)
if first.Code != http.StatusCreated {
t.Fatalf("first: status %d\n%s", first.Code, first.Body)
}
var seq int64
readSeq := func() int64 {
var s int64
if err := a.db.G.Raw("SELECT seq FROM decks WHERE sqid = ?", sqid).Scan(&s).Error; err != nil {
t.Fatal(err)
}
return s
}
seq = readSeq()
second := postPicture(t, a, sqid, token, "?alt=Again", onePixelPNG)
if second.Code != http.StatusOK {
t.Fatalf("second: status %d, want 200\n%s", second.Code, second.Body)
}
a1, a2 := jsonObject(t, first), jsonObject(t, second)
if a1["ref"] != a2["ref"] || a1["id"] != a2["id"] || a2["width"] != float64(1) {
t.Errorf("the duplicate answered %v, the first %v", a2, a1)
}
if assets := deckAssets(t, a, token, sqid); len(assets) != 1 {
t.Errorf("the deck has %d assets after the same picture twice: %+v", len(assets), assets)
}
if readSeq() != seq {
t.Error("the duplicate wrote to the document")
}
}
// TestWhatIsNotAPictureIsRefused: over 20 MiB is 413; anything that is
// not a PNG, JPEG or WebP that decodes at a size pictures allow is 422.
// Nothing is registered.
func TestWhatIsNotAPictureIsRefused(t *testing.T) {
a, _, token, sqid := agentPictures(t)
big := append(append([]byte{}, onePixelPNG...), bytes.Repeat([]byte{0}, 20<<20)...)
// A PNG whose header, checksum right, declares 40000 x 1: it decodes
// as far as its size, which is over the 30000 a picture may be.
wide := append([]byte{}, onePixelPNG...)
wide[16], wide[17], wide[18], wide[19] = 0, 0, 0x9c, 0x40
binary.BigEndian.PutUint32(wide[29:33], crc32.ChecksumIEEE(wide[12:29]))
if cfg, err := png.DecodeConfig(bytes.NewReader(wide)); err != nil || cfg.Width != 40000 {
t.Fatalf("the wide PNG is not a valid header of width 40000: %v %+v", err, cfg)
}
// 10000 x 10000: each edge allowed, the 100 megapixels together not.
square := append([]byte{}, onePixelPNG...)
binary.BigEndian.PutUint32(square[16:20], 10000)
binary.BigEndian.PutUint32(square[20:24], 10000)
binary.BigEndian.PutUint32(square[29:33], crc32.ChecksumIEEE(square[12:29]))
if cfg, err := png.DecodeConfig(bytes.NewReader(square)); err != nil || cfg.Width != 10000 {
t.Fatalf("the square PNG is not a valid header of 10000 x 10000: %v %+v", err, cfg)
}
if cfg, err := webp.DecodeConfig(bytes.NewReader(hugeWebP())); err != nil || cfg.Width != 30000 || cfg.Height != 30000 {
t.Fatalf("the huge WebP is not a valid header of 30000 x 30000: %v %+v", err, cfg)
}
for name, c := range map[string]struct {
body []byte
status int
code string
}{
"too big": {big, http.StatusRequestEntityTooLarge, "too_large"},
"too many pixels together": {square, http.StatusUnprocessableEntity, "not_an_image"},
"a webp header of 30000 x 30000": {hugeWebP(), http.StatusUnprocessableEntity, "not_an_image"},
"text": {[]byte("hello, this is not a picture"), http.StatusUnprocessableEntity, "not_an_image"},
"html": {[]byte("