Add explicit login functionality

This commit is contained in:
2026-09-13 00:50:15 +02:00
parent 74bfdbfd8a
commit 1b77cdd165
14 changed files with 629 additions and 258 deletions
+278 -77
View File
@@ -651,57 +651,165 @@ func assertNoDebris(t *testing.T, dir string) {
// --- remembered tokens ---------------------------------------------------
// A browser form post that carries a token and the remember box gets a cookie
// back, and that cookie then authenticates later uploads on its own.
func TestTokenIsRememberedInACookie(t *testing.T) {
// Logging in is what stores a token; uploading never touches the cookie.
func TestLoginStoresTheToken(t *testing.T) {
h := newHarness(t, nil)
resp := h.formUpload(t, map[string]string{"token": h.token, "remember": "1"}, "a.bin", "one")
if resp.StatusCode != http.StatusCreated {
t.Fatalf("status = %s", resp.Status)
}
resp := h.postForm(t, "/login", url.Values{"token": {h.token}, "persist": {"1"}}, nil)
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("status = %s, want 303", resp.Status)
}
if loc := resp.Header.Get("Location"); loc != "/" {
t.Errorf("Location = %q, want /", loc)
}
cookie := findCookie(resp, tokenCookie)
if cookie == nil {
t.Fatal("no token cookie was set")
t.Fatal("logging in set no cookie")
}
if cookie.Value != h.token {
t.Error("the cookie does not hold the token")
}
if !cookie.HttpOnly {
t.Error("the token cookie is readable by scripts")
t.Error("the session cookie is readable by scripts")
}
if cookie.SameSite != http.SameSiteStrictMode {
t.Error("the token cookie is not SameSite=Strict, so it is CSRF-exposed")
t.Error("the session cookie is not SameSite=Strict, so it is CSRF-exposed")
}
if cookie.MaxAge <= 0 {
t.Error("'stay logged in' did not persist the cookie")
}
// The cookie alone is now enough to claim a vanity name, which anonymous
// callers cannot do.
// The session alone is now enough to claim a custom name.
req, _ := http.NewRequest("POST", h.ts.URL+"/api/upload", strings.NewReader("two"))
req.Header.Set("Accept", "application/json")
req.Header.Set("Vanity", "remembered")
req.Header.Set("Vanity", "session-upload")
req.AddCookie(cookie)
resp, err := h.ts.Client().Do(req)
up, err := h.ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusCreated {
t.Fatalf("upload with only the cookie: status = %s", resp.Status)
if up.StatusCode != http.StatusCreated {
t.Fatalf("upload with only the session: status = %s", up.Status)
}
if res := decode[uploadResult](t, resp); res.ID != "remembered" {
t.Errorf("id = %q, want remembered", res.ID)
if res := decode[uploadResult](t, up); res.ID != "session-upload" {
t.Errorf("id = %q, want session-upload", res.ID)
}
}
// A typed token wins over whatever the browser remembered.
func TestExplicitTokenBeatsTheCookie(t *testing.T) {
// Without "stay logged in" the cookie must die with the browser.
func TestLoginWithoutPersistIsASessionCookie(t *testing.T) {
h := newHarness(t, nil)
resp := h.formUpload(t, map[string]string{"token": h.token, "remember": "1"}, "a.bin", "x")
cookie := findCookie(resp, tokenCookie)
resp := h.postForm(t, "/login", url.Values{"token": {h.token}}, nil)
resp.Body.Close()
c := findCookie(resp, tokenCookie)
if c == nil {
t.Fatal("no cookie was set")
}
if c.MaxAge != 0 || !c.Expires.IsZero() {
t.Errorf("cookie carries a lifetime (MaxAge=%d), want a session cookie", c.MaxAge)
}
}
func TestLoginRejectsAnUnknownToken(t *testing.T) {
h := newHarness(t, nil)
resp := h.postForm(t, "/login", url.Values{"token": {"not-a-token"}}, nil)
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
resp = h.formUploadWith(t, cookie, map[string]string{"token": h.admin, "remember": "1"}, "b.bin", "y")
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("status = %s, want 401", resp.Status)
}
if findCookie(resp, tokenCookie) != nil {
t.Error("a rejected login still set a cookie")
}
if !strings.Contains(string(raw), "not recognised") {
t.Error("the login page does not say what went wrong")
}
}
// Guessing a token at the login form is throttled; a correct one is not.
func TestFailedLoginsAreThrottled(t *testing.T) {
h := newHarness(t, nil)
h.authLimiter = newLimiter(1, 3)
var last *http.Response
for range 5 {
if last != nil {
last.Body.Close()
}
last = h.postForm(t, "/login", url.Values{"token": {"guess"}}, nil)
}
if last.StatusCode != http.StatusTooManyRequests {
t.Fatalf("repeated guesses => %s, want 429", last.Status)
}
last.Body.Close()
resp := h.postForm(t, "/login", url.Values{"token": {h.token}}, nil)
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("a correct token was throttled: %s", resp.Status)
}
}
// The post-login destination is an allowlisted page name, never a URL, so it
// cannot be turned into an open redirect.
func TestLoginRedirectIsAllowlisted(t *testing.T) {
h := newHarness(t, nil)
for _, c := range []struct{ next, want string }{
{"admin", "/admin"},
{"", "/"},
{"https://evil.example.com", "/"},
{"//evil.example.com", "/"},
{"../../etc", "/"},
} {
resp := h.postForm(t, "/login", url.Values{"token": {h.admin}, "next": {c.next}}, nil)
resp.Body.Close()
if loc := resp.Header.Get("Location"); loc != c.want {
t.Errorf("next=%q => Location %q, want %q", c.next, loc, c.want)
}
}
}
func TestLogoutEndsTheSession(t *testing.T) {
h := newHarness(t, nil)
resp := h.postForm(t, "/logout", url.Values{}, &http.Cookie{Name: tokenCookie, Value: h.token})
resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("status = %s, want 303", resp.Status)
}
c := findCookie(resp, tokenCookie)
if c == nil || c.MaxAge >= 0 || c.Value != "" {
t.Fatalf("the session cookie was not cleared: %v", c)
}
}
// Uploading must never change the session, in either direction.
func TestUploadNeverTouchesTheSession(t *testing.T) {
h := newHarness(t, nil)
resp := h.formUpload(t, map[string]string{"token": h.token}, "a.bin", "one")
resp.Body.Close()
if c := findCookie(resp, tokenCookie); c != nil {
t.Errorf("an upload with a one-off token set a session cookie: %v", c)
}
resp = h.formUploadWith(t, &http.Cookie{Name: tokenCookie, Value: h.token},
map[string]string{}, "b.bin", "two")
resp.Body.Close()
if c := findCookie(resp, tokenCookie); c != nil {
t.Errorf("an upload cleared the session: %v", c)
}
}
// A one-off token on the form wins over the logged-in session.
func TestExplicitTokenBeatsTheCookie(t *testing.T) {
h := newHarness(t, nil)
cookie := &http.Cookie{Name: tokenCookie, Value: h.token}
resp := h.formUploadWith(t, cookie, map[string]string{"token": h.admin}, "b.bin", "y")
defer resp.Body.Close()
res := decode[uploadResult](t, resp)
@@ -710,42 +818,11 @@ func TestExplicitTokenBeatsTheCookie(t *testing.T) {
t.Fatal(err)
}
if m.Owner != "boss" {
t.Errorf("owner = %q, want boss: the cookie shadowed the typed token", m.Owner)
t.Errorf("owner = %q, want boss: the session shadowed the one-off token", m.Owner)
}
}
// Leaving the box unchecked clears a token the browser had remembered.
func TestUncheckingRememberForgetsTheCookie(t *testing.T) {
h := newHarness(t, nil)
resp := h.formUpload(t, map[string]string{"token": h.token, "remember": "1"}, "a.bin", "x")
cookie := findCookie(resp, tokenCookie)
resp.Body.Close()
resp = h.formUploadWith(t, cookie, map[string]string{}, "b.bin", "y")
defer resp.Body.Close()
cleared := findCookie(resp, tokenCookie)
if cleared == nil || cleared.MaxAge >= 0 {
t.Fatalf("the cookie was not cleared: %v", cleared)
}
}
func TestForgetEndpointClearsTheCookie(t *testing.T) {
h := newHarness(t, nil)
req, _ := http.NewRequest("POST", h.ts.URL+"/api/forget", nil)
req.Header.Set("Accept", "application/json")
req.AddCookie(&http.Cookie{Name: tokenCookie, Value: h.token})
resp, err := h.ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
c := findCookie(resp, tokenCookie)
if c == nil || c.MaxAge >= 0 || c.Value != "" {
t.Fatalf("the cookie was not cleared: %v", c)
}
}
// A revoked token left in a cookie must not wedge the page.
// A session whose token has since been revoked must not wedge the page.
func TestStaleCookieIsDropped(t *testing.T) {
h := newHarness(t, nil)
req, _ := http.NewRequest("GET", h.ts.URL+"/", nil)
@@ -762,14 +839,17 @@ func TestStaleCookieIsDropped(t *testing.T) {
t.Error("a stale cookie was not dropped")
}
page, _ := io.ReadAll(resp.Body)
if strings.Contains(string(page), "Uploading as") {
if !strings.Contains(string(page), "no longer valid") {
t.Error("the page does not explain that the session ended")
}
if !strings.Contains(string(page), "<em>anonymous</em>") {
t.Error("the page claims an identity it could not resolve")
}
}
// The index page resolves a remembered token server-side, so the limits shown
// are the caller's real ones even though the cookie is unreadable by script.
func TestIndexShowsTheRememberedIdentity(t *testing.T) {
// The session is resolved server-side, so every page agrees about who you are
// even though the cookie is unreadable by script.
func TestIndexShowsWhoIsLoggedIn(t *testing.T) {
h := newHarness(t, nil)
req, _ := http.NewRequest("GET", h.ts.URL+"/", nil)
req.AddCookie(&http.Cookie{Name: tokenCookie, Value: h.token})
@@ -779,8 +859,8 @@ func TestIndexShowsTheRememberedIdentity(t *testing.T) {
}
defer resp.Body.Close()
page, _ := io.ReadAll(resp.Body)
if !strings.Contains(string(page), "Uploading as <strong>friend</strong>") {
t.Error("the page does not show the remembered identity")
if !strings.Contains(string(page), ">friend<") {
t.Error("the page does not show who is logged in")
}
if strings.Contains(string(page), h.token) {
t.Error("the page echoes the token back into the HTML")
@@ -790,7 +870,7 @@ func TestIndexShowsTheRememberedIdentity(t *testing.T) {
// The per-object delete token must still work when a cookie is also present.
func TestCookieDoesNotShadowTheDeleteToken(t *testing.T) {
h := newHarness(t, nil)
// Uploaded anonymously, so the remembered token owns nothing here.
// Uploaded anonymously, so the logged-in token owns nothing here.
res := decode[uploadResult](t, h.upload(t, []byte("x"), nil))
form := strings.NewReader("token=" + res.DeleteToken)
@@ -808,17 +888,6 @@ func TestCookieDoesNotShadowTheDeleteToken(t *testing.T) {
}
}
// An API caller sending a bearer token manages its own credentials and should
// not be handed a cookie it never asked for.
func TestBearerCallersAreNotGivenACookie(t *testing.T) {
h := newHarness(t, nil)
resp := h.upload(t, []byte("x"), map[string]string{"Authorization": "Bearer " + h.token})
defer resp.Body.Close()
if c := findCookie(resp, tokenCookie); c != nil {
t.Errorf("a cookie was set for a bearer-token upload: %v", c)
}
}
func findCookie(resp *http.Response, name string) *http.Cookie {
for _, c := range resp.Cookies() {
if c.Name == name {
@@ -1064,7 +1133,7 @@ func TestAdminPageAccessControl(t *testing.T) {
}
// The cookie is the credential a browser actually uses for this page.
func TestAdminPageAcceptsTheRememberedCookie(t *testing.T) {
func TestAdminPageAcceptsTheSession(t *testing.T) {
h := newHarness(t, nil)
req, _ := http.NewRequest("GET", h.ts.URL+"/admin", nil)
req.AddCookie(&http.Cookie{Name: tokenCookie, Value: h.admin})
@@ -1276,6 +1345,9 @@ func TestFormFieldsOverrideTheHeaders(t *testing.T) {
// --- deleting from the info page -----------------------------------------
// postForm submits a form the way a browser would, without following the
// redirect: where these posts send you, and what they set on the way, is
// usually the thing under test.
func (h *harness) postForm(t *testing.T, path string, form url.Values, cookie *http.Cookie) *http.Response {
t.Helper()
req, _ := http.NewRequest("POST", h.ts.URL+path, strings.NewReader(form.Encode()))
@@ -1284,7 +1356,11 @@ func (h *harness) postForm(t *testing.T, path string, form url.Values, cookie *h
if cookie != nil {
req.AddCookie(cookie)
}
resp, err := h.ts.Client().Do(req)
client := *h.ts.Client()
client.CheckRedirect = func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
@@ -1398,7 +1474,7 @@ func TestInfoPageOffersADirectButtonToAnOwner(t *testing.T) {
// delayed by someone else's failed attempts.
func TestFailedDeletesAreThrottledAndSuccessIsNot(t *testing.T) {
h := newHarness(t, nil)
h.deleteLimiter = newLimiter(1, 3)
h.authLimiter = newLimiter(1, 3)
res := decode[uploadResult](t, h.upload(t, []byte("x"), nil))
@@ -1423,3 +1499,128 @@ func TestFailedDeletesAreThrottledAndSuccessIsNot(t *testing.T) {
t.Fatalf("the correct token was throttled: %s", resp.Status)
}
}
// --- cross-site posts ----------------------------------------------------
// A login form needs no cookie to submit, so SameSite does not cover it: a
// hostile page could otherwise sign a visitor into an account it controls and
// collect whatever they upload next. Browsers label their own requests, and
// those labels are checked on every state-changing route.
func TestCrossOriginPostsAreRejected(t *testing.T) {
h := newHarness(t, nil)
paths := []string{"/login", "/logout", "/api/upload", "/api/d/anything/delete"}
hostile := []map[string]string{
{"Origin": "https://evil.example.com"},
{"Sec-Fetch-Site": "cross-site"},
{"Sec-Fetch-Site": "same-site"},
}
for _, path := range paths {
for _, headers := range hostile {
req, _ := http.NewRequest("POST", h.ts.URL+path, strings.NewReader("token=x"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := h.ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("POST %s with %v => %s, want 403", path, headers, resp.Status)
}
}
}
}
// The page's own posts, and API clients that label nothing, must still work.
func TestSameOriginAndUnlabelledPostsAreAccepted(t *testing.T) {
h := newHarness(t, nil)
for _, headers := range []map[string]string{
{}, // curl and friends
{"Sec-Fetch-Site": "same-origin"}, // the page itself
{"Sec-Fetch-Site": "none"}, // typed into the bar
{"Origin": "http://" + strings.TrimPrefix(h.ts.URL, "http://")}, // older browser
} {
req, _ := http.NewRequest("POST", h.ts.URL+"/login",
strings.NewReader(url.Values{"token": {h.token}}.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := h.ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("POST /login with %v => %s, want 200", headers, resp.Status)
}
}
}
// The header is the only navigation there is, so it has to tell the truth
// about the session on every page.
func TestHeaderReflectsTheSession(t *testing.T) {
h := newHarness(t, nil)
for _, c := range []struct {
who string
token string
present []string
absent []string
}{
{"anonymous", "", []string{`href="/login"`}, []string{`action="/logout"`, `href="/admin"`}},
{"a plain token", h.token, []string{`action="/logout"`, ">friend<"}, []string{`href="/login"`, `href="/admin"`}},
{"an admin token", h.admin, []string{`action="/logout"`, `href="/admin"`, ">boss<"}, []string{`href="/login"`}},
} {
for _, path := range []string{"/", "/login"} {
req, _ := http.NewRequest("GET", h.ts.URL+path, nil)
if c.token != "" {
req.AddCookie(&http.Cookie{Name: tokenCookie, Value: c.token})
}
resp, err := h.ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
page := string(raw)
for _, want := range c.present {
if !strings.Contains(page, want) {
t.Errorf("GET %s as %s: missing %q", path, c.who, want)
}
}
for _, unwanted := range c.absent {
if strings.Contains(page, unwanted) {
t.Errorf("GET %s as %s: unexpectedly offers %q", path, c.who, unwanted)
}
}
}
}
}
// The upload form keeps a one-off token field, so a quick upload under another
// token does not require logging in and out.
func TestUploadPageKeepsTheOneOffTokenField(t *testing.T) {
h := newHarness(t, nil)
resp := h.get(t, "/", "")
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
page := string(raw)
if !strings.Contains(page, `name="token"`) {
t.Error("the upload form has no one-off token field")
}
if !strings.Contains(page, "does not log you in") {
t.Error("the form does not explain that the field is one-off")
}
// The limits are rendered, not fetched, so no script is needed to show them.
if !strings.Contains(page, `data-max-size="1048576"`) {
t.Error("the form does not carry the server-rendered size limit")
}
}