package webui import ( "crypto/tls" "net/http" "net/http/httptest" "testing" ) // sendCookie attaches a cookie to a request as a browser sends it: a name and // a value, with none of the attributes a response sets. func sendCookie(req *http.Request, name, value string) { req.Header.Add("Cookie", name+"="+value) } // TestSessionCookiesSecureBehindProxy pins that a cookie is marked Secure // whenever the browser reached the dashboard over HTTPS, including through a // trusted proxy that terminates TLS. func TestSessionCookiesSecureBehindProxy(t *testing.T) { tests := []struct { name string tls bool forwarded string trust bool wantSecure bool }{ {"direct https", true, "", false, true}, {"plain http", false, "", false, false}, {"trusted proxy terminating https", false, "https", true, true}, {"untrusted forwarded header", false, "https", false, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := &Server{TrustForwardedHeaders: tt.trust} r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) if tt.tls { r.TLS = &tls.ConnectionState{} } if tt.forwarded != "" { r.Header.Set("X-Forwarded-Proto", tt.forwarded) } w := httptest.NewRecorder() s.setOrgCookie(w, r, "acme") cookies := w.Result().Cookies() if len(cookies) != 1 || cookies[0].Secure != tt.wantSecure { t.Fatalf("cookies = %+v, want one with Secure=%v", cookies, tt.wantSecure) } }) } }