package handlers import ( "maps" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) // generatePost submits the /generate form with a valid session and CSRF token // plus the caller's extra fields, returning the recorder. func generatePost( t *testing.T, extra url.Values, ) *httptest.ResponseRecorder { t.Helper() h, srv := newCSRFTestRouter(t) sessionCookie := newSessionCookie(t, h) cookies, token := csrfCredentials(t, srv, []*http.Cookie{sessionCookie}) cookies = append(cookies, sessionCookie) form := url.Values{ sourceURLField: {testSourceURL}, csrfTokenField: {token}, } maps.Copy(form, extra) return postForm(srv, "/generate", cookies, form) } // TestGeneratePostRejectsNonNumericWidth verifies that a non-numeric width is // rejected with 400 naming the field rather than being coerced to 0 and // minting a 0-width token. func TestGeneratePostRejectsNonNumericWidth(t *testing.T) { t.Parallel() rec := generatePost(t, url.Values{"width": {"abc"}}) if rec.Code != http.StatusBadRequest { t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest) } if strings.Contains(rec.Body.String(), "/v1/e/") { t.Error("a token was generated for non-numeric width") } } // TestGeneratePostRejectsOverLimitWidth verifies that a width beyond // MaxDimension is rejected at generation time so an unusable token cannot be // minted. func TestGeneratePostRejectsOverLimitWidth(t *testing.T) { t.Parallel() rec := generatePost(t, url.Values{"width": {"100000"}}) if rec.Code != http.StatusBadRequest { t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest) } if strings.Contains(rec.Body.String(), "/v1/e/") { t.Error("a token was generated for an over-limit width") } }