Skip to content

Commit

Permalink
[cpackget] Handle Cookie headers in HTTP GET requests when required
Browse files Browse the repository at this point in the history
  • Loading branch information
brondani committed Dec 13, 2024
1 parent 29d13de commit 5ee5cef
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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

0 comments on commit 5ee5cef

Please sign in to comment.