Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cpackget] Handle Cookie headers in HTTP GET requests when required #406

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions cmd/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,20 @@ func DownloadFile(URL string, timeout int) (string, error) {
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusForbidden {
cookie := resp.Header.Get("Set-Cookie")
if len(cookie) > 0 {
// add cookie and resend GET request
log.Debugf("Cookie: %s", cookie)
req.Header.Add("Cookie", cookie)
resp, err = client.Do(req)
if err != nil {
log.Error(err)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrFailedDownloadingFile)
}
}
}

if resp.StatusCode != http.StatusOK {
log.Debugf("bad status: %s", resp.Status)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrBadRequest)
Expand Down
29 changes: 29 additions & 0 deletions cmd/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,35 @@ func TestDownloadFile(t *testing.T) {
assert.Equal(bytes, goodResponse)
})

t.Run("test download set cookie", func(t *testing.T) {
fileName := "file.txt"
defer os.Remove(fileName)
goodResponse := []byte("all good")
cookieContent := "cookie=test"
goodServer := httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
cookie := r.Header.Get("Cookie")
if len(cookie) > 0 {
if cookie == cookieContent {
fmt.Fprint(w, string(goodResponse))
}
} else {
w.Header().Add("Set-Cookie", cookieContent)
w.WriteHeader(http.StatusForbidden)
}
},
),
)
url := goodServer.URL + "/" + fileName
_, err1 := utils.DownloadFile(url, 0)
assert.Nil(err1)
assert.True(utils.FileExists(fileName))
bytes, err2 := os.ReadFile(fileName)
assert.Nil(err2)
assert.Equal(bytes, goodResponse)
})

t.Run("test download uses cache", func(t *testing.T) {
fileName := "file.txt"
defer os.Remove(fileName)
Expand Down
Loading