diff --git a/cmd/webtest/session.go b/cmd/webtest/session.go index 5118813..f091ff3 100644 --- a/cmd/webtest/session.go +++ b/cmd/webtest/session.go @@ -105,10 +105,16 @@ func saveCookieJar(path string, jar *cookiejar.Jar, hosts []string) error { } var out []storedCookie for _, host := range hosts { - for _, scheme := range [...]string{"https", "http"} { - for _, c := range jar.Cookies(&url.URL{Scheme: scheme, Host: host}) { - out = append(out, storedCookie{Name: c.Name, Value: c.Value, Domain: host, Path: c.Path, Expires: c.Expires}) - } + // "https" alone is enough: cookiejar stores by domain, not by + // scheme — scheme only GATES a Secure-flagged cookie (hidden from + // an http:// query), never partitions storage, so an "https" + // query already returns every cookie (secure or not) a real + // request to this host would carry. Querying "http" too double- + // counted every non-secure cookie (confirmed directly: a live + // smoke-test run against a plain-http test server produced two + // identical entries for the one cookie it set). + for _, c := range jar.Cookies(&url.URL{Scheme: "https", Host: host}) { + out = append(out, storedCookie{Name: c.Name, Value: c.Value, Domain: host, Path: c.Path, Expires: c.Expires}) } } data, err := json.MarshalIndent(out, "", " ") diff --git a/cmd/webtest/session_test.go b/cmd/webtest/session_test.go index 7c346eb..35b4028 100644 --- a/cmd/webtest/session_test.go +++ b/cmd/webtest/session_test.go @@ -4,6 +4,7 @@ package main import ( + "encoding/json" "net/http" "net/url" "os" @@ -61,6 +62,34 @@ func TestSaveAndLoadCookieJarRoundtrip(t *testing.T) { } } +// TestSaveCookieJarNoDuplicateEntries is the regression test for a real +// bug a live smoke-test run (building the actual binary, logging into a +// real local test server) caught: saveCookieJar's own on-disk JSON array +// held the SAME cookie twice. The earlier roundtrip test above didn't +// catch it because reloading collapses duplicate (name, domain, path) +// entries back down to one when SetCookies is called — the bug was only +// visible by reading the raw file, not by reloading it. +func TestSaveCookieJarNoDuplicateEntries(t *testing.T) { + path := filepath.Join(t.TempDir(), "cookies.json") + jar, _ := loadCookieJar(filepath.Join(t.TempDir(), "nope.json")) + jar.SetCookies(&url.URL{Scheme: "http", Host: "plain.test"}, []*http.Cookie{{Name: "session", Value: "x", Path: "/"}}) + + if err := saveCookieJar(path, jar, []string{"plain.test"}); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var stored []storedCookie + if err := json.Unmarshal(data, &stored); err != nil { + t.Fatal(err) + } + if len(stored) != 1 { + t.Fatalf("saved cookie file has %d entries for one cookie, want exactly 1: %+v", len(stored), stored) + } +} + func TestSaveCookieJarOnlyNamedHosts(t *testing.T) { path := filepath.Join(t.TempDir(), "cookies.json") jar, _ := loadCookieJar(filepath.Join(t.TempDir(), "nope.json"))