Skip to content

Commit 8681f54

Browse files
committedFeb 24, 2024
Move cookiejar change to the right place
InitHTTP overrides the default client created in the starlarkhttp module. And InitHTTP is called from the render and other commands. So, original commit would have had no effect, since that client isn't used in practice. This is where we need to add the cookie jar
1 parent 04f5edc commit 8681f54

File tree

6 files changed

+66
-57
lines changed

6 files changed

+66
-57
lines changed
 

‎runtime/httpcache.go

+11
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ import (
99
"fmt"
1010
"math/rand"
1111
"net/http"
12+
"net/http/cookiejar"
1213
"net/http/httputil"
1314
"strconv"
1415
"strings"
1516
"time"
1617

1718
"github.com/pkg/errors"
19+
"golang.org/x/net/publicsuffix"
1820
"tidbyt.dev/pixlet/runtime/modules/starlarkhttp"
1921
)
2022

@@ -55,7 +57,16 @@ func InitHTTP(cache Cache) {
5557
transport: http.DefaultTransport,
5658
}
5759

60+
// Providing a cookie jar allows sessions and redirects to work properly. With a
61+
// jar present, any cookies set in a response will automatically be added to
62+
// subsequent requests. This means that we can follow redirects after logging into
63+
// a session. Without a jar, any cookies will be dropped from redirects unless explicitly
64+
// set in the original outgoing request.
65+
// https://cs.opensource.google/go/go/+/master:src/net/http/client.go;drc=4c394b5638cc2694b1eff6418bc3e7db8132de0e;l=88
66+
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) // never returns non-nil err
67+
5868
httpClient := &http.Client{
69+
Jar: jar,
5970
Transport: cc,
6071
Timeout: HTTPTimeout * 2,
6172
}

‎runtime/httpcache_test.go

+44
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ import (
44
"fmt"
55
"math/rand"
66
"net/http"
7+
"net/http/httptest"
78
"os"
9+
"strings"
810
"testing"
911
"time"
1012

1113
"github.com/stretchr/testify/assert"
14+
"go.starlark.net/starlark"
1215
)
1316

1417
func TestInitHTTP(t *testing.T) {
@@ -182,3 +185,44 @@ func TestDetermineTTLNoHeaders(t *testing.T) {
182185
ttl := DetermineTTL(req, res)
183186
assert.Equal(t, MinRequestTTL, ttl)
184187
}
188+
189+
func TestSetCookieOnRedirect(t *testing.T) {
190+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
191+
// Requests to "/#" set a cookie and redirect to /destination
192+
if strings.HasSuffix(r.URL.Path, "/#") {
193+
w.Header().Set("Set-Cookie", "doodad=foobar; path=/; HttpOnly")
194+
w.Header().Set("Location", "/destination")
195+
w.WriteHeader(302)
196+
return
197+
}
198+
// Requests to /destination must have cookie set
199+
if strings.HasSuffix(r.URL.Path, "/destination") {
200+
c, err := r.Cookie("doodad")
201+
if err != nil {
202+
t.Errorf("Expected cookie `doodad` not present") // Occurs if client has no cookie jar
203+
}
204+
if c.Value != "foobar" {
205+
t.Errorf("Cookie `doodad` value mismatch. Expected foobar, got %s", c.Value)
206+
}
207+
if _, err := w.Write([]byte(`{"hello":"world"}`)); err != nil {
208+
t.Fatal(err)
209+
}
210+
return
211+
}
212+
t.Errorf("Unexpected path requested: %s", r.URL.Path)
213+
}))
214+
215+
starlark.Universe["test_server_url"] = starlark.String(ts.URL)
216+
c := NewInMemoryCache()
217+
InitHTTP(c)
218+
219+
b, err := os.ReadFile("testdata/httpredirect.star")
220+
assert.NoError(t, err)
221+
222+
app := &Applet{}
223+
err = app.Load("httpredirect", "httpredirect.star", b, nil)
224+
assert.NoError(t, err)
225+
226+
_, err = app.Run(map[string]string{})
227+
assert.NoError(t, err)
228+
}

‎runtime/modules/starlarkhttp/starlarkhttp.go

+1-12
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,13 @@ import (
3232
"io"
3333
"mime/multipart"
3434
"net/http"
35-
"net/http/cookiejar"
3635
"net/url"
3736
"strconv"
3837
"strings"
3938

4039
util "github.com/qri-io/starlib/util"
4140
"go.starlark.net/starlark"
4241
"go.starlark.net/starlarkstruct"
43-
"golang.org/x/net/publicsuffix"
4442
)
4543

4644
// AsString unquotes a starlark string value
@@ -53,18 +51,9 @@ func AsString(x starlark.Value) (string, error) {
5351
const ModuleName = "http.star"
5452

5553
var (
56-
// Providing a cookie jar allows sessions and redirects to work properly. With a
57-
// jar present, any cookies set in a response will automatically be added to
58-
// subsequent requests. This means that we can follow redirects after logging into
59-
// a session. Without a jar, any cookies will be dropped from redirects unless explicitly
60-
// set in the original outgoing request.
61-
// https://cs.opensource.google/go/go/+/master:src/net/http/client.go;drc=4c394b5638cc2694b1eff6418bc3e7db8132de0e;l=88
62-
jar, _ = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
6354
// StarlarkHTTPClient is the http client used to create the http module. override with
6455
// a custom client before calling LoadModule
65-
StarlarkHTTPClient = &http.Client{
66-
Jar: jar,
67-
}
56+
StarlarkHTTPClient = http.DefaultClient
6857
// StarlarkHTTPGuard is a global RequestGuard used in LoadModule. override with a custom
6958
// implementation before calling LoadModule
7059
StarlarkHTTPGuard RequestGuard

‎runtime/modules/starlarkhttp/starlarkhttp_test.go

-38
Original file line numberDiff line numberDiff line change
@@ -140,41 +140,3 @@ func TestSetBody(t *testing.T) {
140140
}
141141
}
142142
}
143-
144-
func TestSetCookieOnRedirect(t *testing.T) {
145-
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
146-
// Requests to "/#" set a cookie and redirect to /destination
147-
if strings.HasSuffix(r.URL.Path, "/#") {
148-
w.Header().Set("Set-Cookie", "doodad=foobar; path=/; HttpOnly")
149-
w.Header().Set("Location", "/destination")
150-
w.WriteHeader(302)
151-
return
152-
}
153-
// Requests to /destination must have cookie set
154-
if strings.HasSuffix(r.URL.Path, "/destination") {
155-
c, err := r.Cookie("doodad")
156-
if err != nil {
157-
t.Errorf("Expected cookie `doodad` not present")
158-
}
159-
if c.Value != "foobar" {
160-
t.Errorf("Cookie `doodad` value mismatch. Expected foobar, got %s", c.Value)
161-
}
162-
if _, err := w.Write([]byte(`{"hello":"world"}`)); err != nil {
163-
t.Fatal(err)
164-
}
165-
return
166-
}
167-
t.Errorf("Unexpected path requested: %s", r.URL.Path)
168-
}))
169-
starlark.Universe["test_server_url"] = starlark.String(ts.URL)
170-
171-
thread := &starlark.Thread{Name: "unittests/setcookieonredirect", Load: testdata.NewLoader(starlarkhttp.LoadModule, starlarkhttp.ModuleName)}
172-
starlarktest.SetReporter(thread, t)
173-
174-
// Execute test file
175-
_, err := starlark.ExecFile(thread, "testdata/test_redirect.star", nil, nil)
176-
if err != nil {
177-
t.Error(err)
178-
}
179-
180-
}

‎runtime/modules/starlarkhttp/testdata/test_redirect.star

-7
This file was deleted.

‎runtime/testdata/httpredirect.star

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
load("http.star", "http")
2+
load("assert.star", "assert")
3+
load("render.star", "render")
4+
5+
def main():
6+
res_1 = http.post(test_server_url + "/#")
7+
assert.eq(res_1.status_code, 200)
8+
assert.eq(res_1.body(), '{"hello":"world"}')
9+
assert.eq(res_1.json(), {"hello": "world"})
10+
return render.Root(child=render.Text("pass"))

0 commit comments

Comments
 (0)